1

I am implementing a server/client program. I need create multiple thread in server to handle message from client. When I compiled the code, there is an error

Exception in thread "Thread-1" java.lang.NullPointerException
at server.run(Program.java:59)

Line 59 is

BufferedReader inFromClient = new BufferedReader(new 
                 InputStreamReader(sSock.getInputStream()));

which is used to read message from client side.

My program code is:

class Program {
  public static void main(String[] args) throws UnknownHostException, IOException{
      // Program runs as a Server
      if(args.length == 2) {
      String host = args[0];
      int port = Integer.parseInt(args[1]);
      String fileName = "serverFile";
      ServerSocket sSock = null;

      // Open a server socket.
      try {
         sSock = new ServerSocket(port);
      }catch(Exception e) {
         System.out.println("Error: cannot open server socket");
         System.exit(1); // Handle exceptions.
      }

      System.out.println("Server is listening on port " + port);

      while(true) {
         new server(sSock.accept(), fileName).start();
      }
    }
  }
}

class server extends Thread {
  // Thread t = Thread.currentThread();

   Socket sSock = null;
   String fileName = null;
   server(Socket sScok,String fileName) {
   this.sSock = sSock;
   this.fileName = fileName;
 }
  @Override
  public void run() {
    try {
      BufferedReader inFromClient = new BufferedReader(new 
                     InputStreamReader(sSock.getInputStream()));
      PrintWriter sendOut = new PrintWriter(sSock.getOutputStream(), 
                     true);
      String s = inFromClient.readLine();
      System.out.println("receive string " + s + "from client");
      sendOut.println("send Ack to you");
    }catch (IOException e) {
      System.out.println("Error: " + e);
   }
 }
}

I have been struggled for a long time...Someone can help would be great.

Xiufen Xu
  • 463
  • 3
  • 6
  • 11
  • Your `server` constructor has an argument called `sScok`, which is never used. Did you mean it to be `sSock`? Also, class names should start with capital letters. – jsheeran Oct 26 '17 at 15:46

2 Answers2

3

You haven't initiated sSock so sSock.getInputStream() throws an exception. The sSock = new ServerSocket(port); line in your main method initiates a different variable named sSock than the one in your server class.

Malt
  • 28,965
  • 9
  • 65
  • 105
3

Socket sSock = null; to begin with, and is never updated

In your constructor you have

server(Socket sScok,String fileName) {
this.sSock = sSock;

The input is sScok instead of sSock, it looks to be a typo, but has a huge effect on your code

Fixing the typo, server(Socket sSock, String fileName) { should do the trick

phflack
  • 2,729
  • 1
  • 9
  • 21