views:

64

answers:

2

I'm using this piece of code that exposes a simple function using a socket:

while (true) {
  try {
    ServerSocket serverSocket = new ServerSocket(7070);
    Socket clientSocket = serverSocket.accept();
    String input = (new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))).readLine();
    synchronized (this.map) {
      ObjectOutputStream o = new ObjectOutputStream(clientSocket.getOutputStream());
      o.writeChars(map.get(input));
      o.close();
    }
    clientSocket.close();
    serverSocket.close();
  } catch(Exception e) {
    e.printStackTrace();
  }
}



What am I doing wrong? logging shows that it gets stuck in the input reception line and it sometimes throws an exception saying that the socket is in use

+2  A: 

For starters, you're create the ServerSocket [i]inside[/i] the loop, which is obviously not what you want. You only want to create it once, then have a loop that constantly reads from the sockets.

Outlaw Programmer
+1  A: 

The readLine() gets stuck because you forgot to flush the output stream of the sender (the other process).

When working with sockets, the computer will buffer some data (usually 4KB) because sending small amounts of data over the network is expensive. Therefore, if you have less data, you need to tell it "send now".

Aaron Digulla