简体   繁体   English

当数据实际通过套接字发送时?

[英]When the data is actually sent through socket?

I am using Java Sockets for communicating between two machines. 我正在使用Java套接字在两台机器之间进行通信。 So when the server receives a message, it process it and replies back with another message. 因此,当服务器收到消息时,它会处理它并回复另一条消息。 I am using TCP protocol. 我正在使用TCP协议。

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? 然后在发送消息后立即,如果我调用套接字的InputStream.available()方法,我是否可以获得从服务器到套接字的实际字节数?

Also is InputStream.available() always returns the full number of bytes which are sending from server, even though the message is extremely large? 另外,InputStream.available()总是返回从服务器发送的完整字节数,即使消息非常大? I heard that TCP has a packet limit, so will that affect InputStream.available()? 我听说TCP有数据包限制,这会影响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). 您几乎不会立即从服务器获得字节(您的客户端应用程序可以更快地检查输入流FAR,而不是任何网络可以传输数据,服务器可以处理和发送响应)。

No, you have no guarantee that a non-zero available() call will return the entire size of the server's response. 不,您无法保证非零的available()调用将返回服务器响应的整个大小。 Quoting from the javadoc: 引用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. 请注意,虽然InputStream的某些实现将返回流中的总字节数,但许多实现不会。 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. 此外,如果消息大小大于TCP数据包最大大小,则消息将被分成几个TCP数据包,在这种情况下,available()可能返回小于消息大小的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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