繁体   English   中英

使用超时与Socket.connect建立连接

[英]Making a connection with Socket.connect using timeout

我正在使用Socket类建立Java TCP连接。

Socket socket = new Socket();
socket.connect(new InetSocketAddress(host,port),50);

我希望此连接快速建立或根本不建立,因此我将50毫秒用作连接超时。

但是,如果我测量这些调用之间的时间,则会得到50毫秒以上的时间:125毫秒,甚至200毫秒。 为了测量时间,我正在使用System.currentMillis()。 我知道这种方法的粒度不是很好,但是+ 100ms的差异只是荒谬的。

connect方法有问题吗? 50毫秒的超时时间太短了吗? 我在Windows 7中使用Java 1.7.0_03。

我觉得这与您如何安排时间有关。 您需要确保立即记录执行前后的时间。

尽管我使用的是Linux,但使用此代码始终能得到51或52的结果:

public class SocketTest {
    public static void main(final String[] args) throws IOException {
        Socket socket = new Socket();
        long start = 0;
        try {
            start = System.nanoTime();
            socket.connect(new InetSocketAddress("192.168.1.100", 80), 50);
        } catch (SocketTimeoutException e) {
            long end = System.nanoTime();
            System.out.println("Time: " + ((end - start) / 1000000));
        }
    }
}

更新:我在Windows 7中尝试过,我得到了50和51。

扩展tdn120的答案,我最终将println移到了。 我一直<100。 我也正在运行Windows 7,Java 7(1.7.0)。

javac -g SocketTest.java && java SocketTest localhost:80 abcd.com:80 localhost:80 localhost:80 localhost:80 
Testing: localhost:80
java.net.SocketTimeoutException: connect timed out
Time: 63
Testing: abcd.com:80
java.net.UnknownHostException: abcd.com
Time: 2350
Testing: localhost:80
java.net.SocketTimeoutException: connect timed out
Time: 50
Testing: localhost:80
java.net.SocketTimeoutException: connect timed out
Time: 50
Testing: localhost:80
java.net.SocketTimeoutException: connect timed out
Time: 50

我的代码如下:

import java.net.*;

public class SocketTest {
    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            args = new String[]{"localhost:80"};
        }
        for (String target: args) {
            test(target);
        }
    }

    private static void test(String target) throws Exception {
        System.out.println("Testing: " + target);
        String[] parts = target.split(":");
        String host = parts[0];
        int port = Integer.valueOf(parts[1]);
        Socket socket = new Socket();
        long start = 0;
        try {
            start = System.nanoTime();
            socket.connect(new InetSocketAddress(host, port), 50);
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            long end = System.nanoTime();
            System.out.println("Time: " + ((end - start) / 1000000));
        }
    }
}

暂无
暂无

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

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