Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top