TFdream / blog

个人技术博客,博文写在 Issues 里。
Apache License 2.0
129 stars 18 forks source link

Java Socket Timeout总结 #313

Open TFdream opened 4 years ago

TFdream commented 4 years ago

转载:https://cloud.tencent.com/developer/article/1039881

1. Socket timeout

Java socket有如下两种timeout:

  1. 建立连接timeout,暂时就叫 connect timeout;
  2. 读取数据timeout,暂时就叫so timeout。

1.1 建立连接connect timeout

当不设置该参数时,指客户端请求和服务端建立tcp连接时,会一直阻塞直到连接建立成功,或抛异常。当设置了connectTimeout, 客户端请求和服务端建立连接时,阻塞时间超过connectTimeout时,就会抛出异常java.net.ConnectException: Connection timed out: connect。

我们看如下精简后的代码,首先是服务端:

serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();

服务端开启ServerSocket监听8080端口,再看客户端:

    socket = new Socket();
    socket.connect(new InetSocketAddress("localhost", 8080));
    System.out.println("Connected.");