简体   繁体   中英

When the data is actually sent through socket?

I am using Java Sockets for communicating between two machines. So when the server receives a message, it process it and replies back with another message. I am using TCP protocol.

My question is, suppose if the network is slow. Then immediately after sending the message, if I call the socket's InputStream.available() method, will I get the actual bytes available from server to the socket?

Also is InputStream.available() always returns the full number of bytes which are sending from server, even though the message is extremely large? I heard that TCP has a packet limit, so will that affect InputStream.available()?

You will almost never have bytes immediately available from a server (your client application can check the input stream FAR faster than just about any network can transfer the data and the server can process and send a response).

No, you have no guarantee that a non-zero available() call will return the entire size of the server's response. Quoting from the javadoc:

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

There is always a delay between the moment server sent data to the stream and client received it. It may be longer or shorter depending on network speed. Besides, if the message size is larger than TCP packet max size then the message will be split into several TCP packets, in this case available() may return value which is less than the message size.

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