As I’m learning about networking and io in Java, I’m slowly building client/server apps to apply what I’m reading on different tutorials. I’m stumped though, and I’ve been trying to figure out why my code isn’t working for a long time. So I decided to turn to SO’s infinite wisdom 🙂
After accepting the client socket connection from localhost, I have this on my server:
BufferedInputStream in = new BufferedInputStream(socket.getInputStream(),Config.BUFFER_SIZE_NET);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream(),Config.BUFFER_SIZE_NET);
String msg = "";
byte buffer[] = new byte[Config.BUFFER_SIZE_READ];
int bytesRead;
System.out.println("Server is waiting for data");
while ((bytesRead = in.read(buffer)) > 0) {
msg = msg + new String(buffer,Config.CHARSET);
}
System.out.println("Server received: "+msg);
After connecting to the server, this is executed on the client after I press a JButton:
BufferedInputStream in = new BufferedInputStream(socket.getInputStream(),Config.BUFFER_SIZE_NET);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream(),Config.BUFFER_SIZE_NET);
String msg = "msg";
try{
out.write(msg.getBytes(Config.CHARSET));
out.flush();
System.out.println("Client sent: "+msg);
}catch(Throwable e){e.printStackTrace();}
After pressing the button on the client, I get this output:
Client sent: msg
On the server side, I get:
Server is waiting for data
If I debug the server, I see it blocked forever on the following line:
while ((bytesRead = in.read(buffer)) > 0) {
No exceptions are thrown. What am I missing here? I had it working before but I’ve done many changes and now I can’t get it back to work.
Note: This is a slightly modified version of the actual code, to make it easier to be reviewed. If you think there’s something relevant missing, let me know!
I got out of the hole I dug myself into. It turns out I wasn’t checking for the end on the data being received, so the code was stuck either blocking for reads, or in the loop that followed. By checking for a specific sequence of bytes in the data read by the server, inside the while loop, I was able to identify the end of the data and break from the loop.
I don’t know if this is the (most) correct answer to the problem above but I solved it in this way, so I’m submitting it as an answer.