Socket code – spot the bug

Recently I’ve been trying to test some code that interacts with a third party over http. I’d like to test as much of the code as possible, not just the code that prepares the data, but also the code that connects to the third party. Obviously I don’t want the test to actually connect to the third party, so I quickly coded up a little server that would listen on a socket for the code to connect.

However, testing the code showed the client hanging. The code contains a pretty basic error, but it took me quite a while to notice it. From the code below, can you figure out what it is?

For the server, I followed the standard procedure:

  • Create a server socket.
  • Wait for the client to connect and then open a new socket for communication, so that the server can continue to listen on the old socket.
  • Open streams for reading and writing.

I set the server to sleep and periodically send data to the client, to make it easy to check the code was working properly.

The code was:

try {
  System.out.println("Trying to start server on port: " + port );
  serverSocket = new ServerSocket(port);
  System.out.println("Server successfully started on port: " + port);
}
catch (IOException e) {
  System.out.println("Could not listen on port: " + port);
  System.exit(-1);
}

Socket clientSocket = null;
try {
  clientSocket = serverSocket.accept();
}
catch (IOException e) {
  System.out.println("Accept failed: " + port);
  System.exit(-1);
}

System.out.println("Client has connected.");
PrintWriter out = null;
try {
  out = new PrintWriter(clientSocket.getOutputStream(), true);
  reader = new BufferedReader(
    new InputStreamReader(clientSocket.getInputStream()));
}
catch (IOException e) {
 e.printStackTrace();
 }

for (int i = 1; i<100; i++) {
  out.write("From server: " + nextResponse);
  try {
    Thread.currentThread().sleep(500);
  }
  catch (InterruptedException e) {
    e.printStackTrace();
  }
}

For the client, I did the following:

  • Started the server on a different thread.
  • Connected to the server.
  • Opened streams for reading and writing.

The code was:

Socket socket = new Socket("localhost",35297);
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(
  new InputStreamReader(socket.getInputStream()));

String fromServer;
while ((fromServer = in.readLine()) != null) {
      	Thread.currentThread().sleep(500);
       	System.out.println("Client trying to read from server...");
        System.out.println("Server: " + fromServer);
}

// shutdown the server
System.out.println("Shutting down server");
s.close();

The code looks fine, but it will hang. Why?

This entry was posted in Java and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

503,517 Spambots Blocked by Simple Comments

HTML tags are not allowed.