Creating a socket server which allows multiple connections via threads and Java

The problem is that currently you’re accepting the connection, but then immediately performing blocking reads on it until it’s closed:

// After a few changes...
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
     clientSocket.getInputStream()));
String nextLine;
while ((nextLine = in.readLine()) != null) {
    System.out.println(nextline);
}

That means the same thread which accepts the connection is trying to handle the connection. That won’t let you use multiple connections at the same time.

Instead, create a class (e.g. ConnectionHandler) which implements Runnable, and has a constructor taking a Socket. Its run method should handle the connection. Then change your code to:

Socket clientSocket = serverSocket.accept();
Runnable connectionHandler = new ConnectionHandler(clientSocket);
new Thread(connectionHandler).start();

That will leave your “main” thread free to wait for the next connection.

(By the way, the KnockKnockProtocol class isn’t really “external” – it’s part of the example. They just didn’t make it very clear that the source is here…)

Leave a Comment