简体   繁体   中英

Null Pointer Exception while trying to run Java multi threaded server

I'm trying to write a java message switch application by using a multi-threaded server and two clients. However I'm stuck at one point as error occurs when I try to run my programmes. Here are my codes for the server:

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

    }
}

I also wrote two classes for client. When I run the server and then the first client, they work as expected. However when I try to run the second client, a NullPointerException is thrown, regarding to the following two lines:

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

I know it's a rather long piece of codes to look at, but I'm really stuck as I can't see the problem here. The earlier single threaded version of server I wrote worked without error, so I know there's something to do about the multithreaded. Any help and advice is really appreciated. Thanks!

connection1 and connection2 are never initialized in your main method, hence you get a NullPointerException when you call in.getInputStream() in your constructor.

Not completely sure what you're trying to achieve, but looks like you might want to move these two lines

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

to your main method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM