Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sockets: output flush causes input read to not block

 
Hung Tang
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My requirement is to write a server that is capable of holding long conversations with the client based on socket programming for Java. I'm using ServerSocket to create TCP sockets. The problem I am running into is that I am not able to do [read, write, read] sequence of operations reliably on my socket. Here is my [read, write, read] code:

1: int numBytesRead = socket.getInputStream().read(buffer);
2: System.out.println(numBytesRead);
3: socket.getOutputStream().write(new byte[] { 'a', 'b', 'c' });
4: socket.getOutputStream().flush();
5: numBytesRead = socket.getInputStream().read(buffer);
6: System.out.println(numBytesRead);

On line 5 in this code, the read operation is NOT blocking and will return -1. After some testing, I concluded that after flushing output [line 4], the input stream will not block anymore. However, if I comment out line 4, the read operation will block again, and will continue to block on subsequent attempts for read before any output flush. What I want is to implement persistent connections which enable me to read client's input, respond, and repeat without closing the socket.

Can anyone give me any ideas as to WHY this is the behaviour to be expected in my code? Why is that a output flush causes my input stream to behave unexpectedly?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably because when the client reads a line, it exits.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could it also be possible that the client sent null through the socket?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic