简体   繁体   English

Java套接字超时不适用

[英]Java socket timeout does not apply

I have this socket implementation in java which uses timeout: 我在使用超时的java中有此套接字实现:

        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), 5000);

        } catch (SocketException e2) {
            System.out.println("Something wrong with the socket: " + e2);
        }

The ip and port is closed, so connection cannot be made. IP和端口已关闭,因此无法建立连接。 But the timeout here does not work. 但是这里的超时不起作用。 It does not wait for 5 seconds and then return an error. 它不会等待5秒钟,然后返回错误。

This code is located in constructor and calls from runnable class. 此代码位于构造函数中,并从可运行类调用。 May this be the reason? 这可能是原因吗?

The connect timeout is the maximum time that connect() will block for. 连接超时是connect()将阻止的长时间。 If there is an immediate connection refusal or other error, you will get it immediately. 如果立即拒绝连接或发生其他错误,您将立即得到它。 In this case the target port wasn't listening so you would have got an immediate ConnectException: connection refused . 在这种情况下,目标端口未在侦听,因此您将立即获得ConnectException: connection refused It isn't obliged to wait for the timeout if the error happens sooner. 如果错误发生得较早,则不必等待超时。 The timeout is really for where there is no response at all. 超时实际上是完全没有响应的地方。 Waiting after an error doesn't make any sense. 错误等待没有任何意义。

Socket socket = new Socket(); 套接字套接字=新的Socket();

// This limits the time allowed to establish a connection //这限制了建立连接的时间

// timeout takes place if connection result is not received with in the specified timeout. //如果在指定的超时时间内未收到连接结果,则会发生超时。

socket.connect(new InetSocketAddress(host, port), timeout); socket.connect(新的InetSocketAddress(主机,端口),超时);

// This stops the request for waiting for response after connection succeeds. //这会在连接成功后停止等待响应的请求。

socket.setSoTimeout(timeout); socket.setSoTimeout(timeout);

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

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