尝试运行Java多线程服务器时出现空指针异常

时间:2015-04-27 23:13:14

标签: java multithreading nullpointerexception serversocket

我正在尝试使用多线程服务器和两个客户端编写java消息切换应用程序。但是,当我尝试运行程序时,由于错误发生,我陷入了困境。以下是我的服务器代码:

public class EchoServer extends Thread {

private static ServerSocket serverSocket;
private static Socket connection1;
private static Socket connection2;
private BufferedReader input;
private PrintWriter output;
final static int portNumber = 4434;

public EchoServer(Socket in,Socket out) throws IOException{

    connection1 = serverSocket.accept();

    connection2 = serverSocket.accept();

    input = new BufferedReader(new InputStreamReader(in.getInputStream()));
    output = new PrintWriter(out.getOutputStream(),true);
}

public void run()
{
    String inputLine;

        while((inputLine=input.readLine())!=null){
            if(inputLine.equalsIgnoreCase("quit"))
                break;
            System.out.println("received:" + inputLine);
            output.println(inputLine);
        }
            System.out.println("received quit,exiting");
    }

public static void main(String args[]){


            serverSocket = new ServerSocket(portNumber);

        System.out.println("listening on port:"+ portNumber);

        EchoServer echoserver1 = new EchoServer(connection1,connection2);
        EchoServer echoserver2 = new EchoServer(connection2,connection1);
        echoserver1.start();
        echoserver2.start();

    }
}

我还为客户写了两个班。当我运行服务器然后运行第一个客户端时,它们按预期工作。但是,当我尝试运行第二个客户端时,抛出NullPointerException,关于以下两行:

        input = new BufferedReader(new InputStreamReader(in.getInputStream()));
        EchoServer echoserver1 = new EchoServer(connection1,connection2);

我知道这是一段相当长的代码,但我真的陷入困境,因为我在这里看不到问题。我编写的早期单线程版本的服务器工作没有错误,所以我知道有关多线程的事情要做。任何帮助和建议真的很感激。谢谢!

1 个答案:

答案 0 :(得分:3)

connection1connection2永远不会在您的main方法中初始化,因此当您在构造函数中调用NullPointerException时,会得到in.getInputStream()

不完全确定你想要实现的目标,但看起来你可能想要移动这两行

connection1 = serverSocket.accept();
connection2 = serverSocket.accept();

到您的main方法。