1

Is there a way to detect the EOF when reading from a TCP Socket whilst the socket connection stays open?

Most of the examples I have seen are something along the lines of:

int n=0;
While((n = read.inStream(data)) != -1){
    destType.write(data, 0, n);
}

However this means that you are forced to create a new connection every time you want to receive a new piece of data. In my case this is a constant stream of images that are sent across the socket as bytes and I would like to process each image without having to close the connection between so that I can have all the images associated with a single user, aswell as it is just more efficient to not constantly open and close connections at a high frequency.

So is there a way to do this or some information on a possible alternative?

Jay
  • 115
  • 2
  • 7

1 Answers1

1

No - if the connection stays open, the stream hasn't reached its end. The idea of a stream reporting EOF and then having more data later goes against the principle of a stream.

If you want to send multiple messages across a TCP stream, the simplest way is to prefix each message with its length:

HEADER BODY
HEADER BODY
HEADER BODY

Then the client will read the header, find out how long the message is, read it, then read the next header, etc.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Or use start message/end message indicators. – Shane Wealti Jan 20 '12 at 13:55
  • @ShaneWealti: While that's possible, it becomes much more client intensive - you have to parse the data as you read it, and work out an escaping strategy for if the data naturally includes the "end message" indicator within it. – Jon Skeet Jan 20 '12 at 14:11
  • I prefer both - an endianness-proof header, starting with SOH, that contains the data length in ASCII and can be structure and sanity-checked, and a terminator that includes a checksum for the header. If the header-check fails or the terminator is bad, all data is discarded until another SOH is received that can start another header-check. – Martin James Jan 21 '12 at 09:49