简体   繁体   English

Java Socket:为什么套接字没有“写超时”

[英]Java Socket:why is there is no “write timeout” for the socket

There is the connecting timeout value passed to connect method, and there is the reading timeout set using setSoTimeout method.有传递给connect方法的连接超时值,有使用setSoTimeout方法设置的读取超时值。 I was wondering why there is no method to set the "writing timeout"?我想知道为什么没有设置“写入超时”的方法? I think there is the writing timeout concept in the TCP Protocol.我认为TCP协议中有写超时的概念。

It wouldn't be much use.不会有多大用处。

In general TCP sending is asynchronous to the application.通常,TCP 发送与应用程序是异步的。 All that send() does is put the data into the socket send buffer. send()所做的只是将数据放入套接字发送缓冲区。 It then returns, while the send buffer is emptied to the network asynchronously.然后它返回,同时发送缓冲区被异步清空到网络。 So there is nothing to timeout.所以没有什么可以超时的。 And the absence of a timeout does not denote that the data has been sent to the peer.并且没有超时并不表示数据已发送到对等方。

send() blocks while the send buffer is full, and it would be possible to implement a timeout on that, and indeed you can do that yourself in non-blocking mode with select() , but the problem is that what timed out could be either the current send or a prior one. send()在发送缓冲区已满时阻塞并且可以在其上实现超时,实际上您可以使用select()在非阻塞模式下自己做到这一点,但问题是超时可能是当前发送或前一个发送。 So delivering a timeout would be rather confusing.因此,提供超时会相当混乱。 Instead what is delivered when all the TCP send timers time out internally is a connection reset.相反,当所有 TCP 发送计时器在内部超时时传递的是连接重置。

I think there is the writing timeout concept in the TCP Protocol.我认为TCP协议中有写超时的概念。

There is indeed, but that's at the level where TCP is asynchronously emptying the socket send buffer.确实有,但那是在 TCP 异步清空套接字发送缓冲区的级别。 It isn't under application control.它不受应用程序控制。

you can first try to connect...if connect fails catch exception您可以先尝试连接...如果连接失败捕获异常

InetSocketAddress sockAdr = new InetSocketAddress(serveradres, 2222);
Socket newsok = new Socket();
int timeout = 2000;
newsok.connect(sockAdr, timeout);

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

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