如何在客户端套接字连接上设置超时?

Var*_*man 36 java sockets

我试图在java中设置客户端套接字上的连接超时.我已将默认连接超时设置为2000,即:

this.socket.connect(this.socketAdd, timeOut);
Run Code Online (Sandbox Code Playgroud)

我正在尝试一个Web应用程序.当用户发出请求时,我将值传递给套接字服务器,但如果我在5秒内没有收到任何响应,则套接字应该断开连接.但在我的情况下,整个请求再次提交.任何人都可以告诉我哪里出错了?

如果我在5秒内没有得到任何响应,我想切断套接字连接.我怎么设置它?任何示例代码都会有帮助.

xyz*_*xyz 44

你甚至可以尝试:

Socket client=new Socket();   
client.connect(new InetSocketAddress(hostip,port_num),connection_time_out); 
Run Code Online (Sandbox Code Playgroud)

  • 这有助于我在服务器不存在或拒绝连接时超时. (4认同)
  • 顺便说一句,`connection_time_out`以毫秒为单位 (2认同)

ani*_*bet 27

把整个事情放在一起:

Socket socket = new Socket();
// This limits the time allowed to establish a connection in the case
// that the connection is refused or server doesn't exist.
socket.connect(new InetSocketAddress(host, port), timeout);
// This stops the request from dragging on after connection succeeds.
socket.setSoTimeout(timeout);
Run Code Online (Sandbox Code Playgroud)


Jim*_*ris 18

您显示的是连接超时,如果在一定时间内无法连接,则会超时.

您的问题意味着您希望在已经连接并发送请求时超时,如果在一定时间内没有响应,您希望超时.

假设你的意思是后者,那么你需要超时,socket.read()这可以通过SO_TIMEOUT使用Socket.setSoTimeout(int timeout)方法设置来完成.如果读取的时间超过指定的毫秒数,则会抛出异常.例如:

this.socket.setSoTimeout(timeOut);
Run Code Online (Sandbox Code Playgroud)

另一种方法是在线程中执行读取,然后在超时时等待线程,并在超时时关闭套接字.