带有BufferedReader的线程“Thread-1”java.lang.NullPointerException中的异常

时间:2017-10-26 15:41:57

标签: java multithreading nullpointerexception bufferedreader serversocket

我正在实施一个服务器/客户端程序。我需要在服务器中创建多个线程来处理来自客户端的消息。编译代码时,出现错误

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

第59行是

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

用于从客户端读取消息。

我的程序代码是:

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);
   }
 }
}

我已经挣扎了很长时间......有人能提供帮助会很棒。

2 个答案:

答案 0 :(得分:3)

您尚未启动sSock,因此sSock.getInputStream()会引发异常。主方法中的sSock = new ServerSocket(port);行会启动一个名为sSock不同的变量,而不是server类中的变量。

答案 1 :(得分:2)

Socket sSock = null;开头,永远不会更新

在您的构造函数中

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

输入为sScok而不是sSock,它看起来是一个拼写错误,但会对您的代码产生巨大影响

修正错字,server(Socket sSock, String fileName) {应该可以解决问题