简体   繁体   中英

What happens to data received by a socket in case of timeout exception during readShort()?

I'm developing a client (Java)/server(C++) application using TCP sockets. The protocol I used is composed of Messages beginning by 2 bytes defining the type of what will be the content of the Message. So basically, the receiving thread waits for data to be received in a loop. But I want to use a timeout with the socket to be notified that the other host takes too long to send data.

receivingSocket.setSoTimeout(durationInMilliseconds);
DataInputStream in = new DataInputStream(receivingSocket.getInputStream());
boolean success = false;
short value = 0;
do {
    try {
        value = in.readShort();// will throw a SocketTimeoutException  in case of timeout, without 2 bytes available from the socket
        success = true;
    } catch (SocketTimeoutException e) {
        /// do something if it happens to often. Otherwise go on with the loop
    }
    } catch (IOException e) {
        /// abort connection in case of other problem 
    }
} while (!success)

Now, what happens if the receiving thread calls in.readShort() at a point where the socket has got only one byte available in its buffer ? Does this byte remain on the socket's stack ? Or is it lost ? In the first case, I could read it next time I call in.readShort(), otherwise it seems lost for good...

readShort() here is an example, my question stands also for readInt(), ...

Thanks for your help,

It isn't specified. I believe the way the implementation works is that the half data is lost, but in any case there's nothing written that says anything else, so you just have to assume the worst.

However in practice this is very unlikely to happen, provided you observe common sense at the sender.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM