Search code examples
javasocketstcpprotocol-buffers

How to get the count of bytes in the SendBuffer of a Socket?


I have a network application where it is possible that the server is not reachable. The client sends on idle time every 30 seconds the string ping\n to the server over a TCP connection so that the server can see if the client is online or not. My server doesn't response at all. If the connection is interrupted and the client goes on to send the "ping" messages the packages will be stored, maybe by the operating system, in a buffer until the server got the packages. If the Server is back online it is possible that the server gets dozens of ping packages at once. Is it possible to get the count of bytes a that buffer?

Edit: How can I get the count bytes which have to be send out by the client?


Solution

  • If you are asking whether or not it is possible to detect, before you call read on a network socket, how many bytes are available to be read, the short answer is no. You can only detect whether or not there are any bytes available to be read but not the number of bytes. The client may also have bytes written to its kernel but blocked by the server's full buffers so the server itself may not know how many bytes are ready to be read. Also, from the client side, there is no way to find out how much data has been written by the client but not consumed by the server.

    The data is buffered both on the client side and the server side but there is no way in Java to be able to see how many bytes are in those buffers. You might be able to get it with some very specific kernel calls in C but it would be very non portable.

    • One thing to consider is to use Socket.setKeepAlive(true) which will use the TCP mechanisms to keep the socket alive. I'm not sure how reliable that is from the server side but it should then get a -1 from the read when the socket times out after the client goes away.
    • Another is to make a separate TCP connection for each ping. If that is too expensive then you can reconnect after a certain number of ping tries.
    • A third thing to consider is to send UDP packets from the client which won't be buffered and are a lot less expensive. You should send more often since there is no retry as well.
    • The server could also send back some sort of response so the client knows that the client knows the socket is still good. It can reconnect if it doesn't get the response.