Meaningless Drivel is fun!*
The moose likes Sockets and Internet Protocols and the fly likes sockets: output flush causes input read to not block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "sockets: output flush causes input read to not block" Watch "sockets: output flush causes input read to not block" New topic
Author

sockets: output flush causes input read to not block

Hung Tang
Ranch Hand

Joined: Feb 14, 2002
Posts: 148
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

Probably because when the client reads a line, it exits.


[Jess in Action][AskingGoodQuestions]
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
Could it also be possible that the client sent null through the socket?
 
GeeCON Prague 2014
 
subject: sockets: output flush causes input read to not block