socket超时设立

socket超时设置

        在使用socket编程时,肯定会遇到设置超时的问题。有些人可能会认为Socket类的setSoTimeout(soTimeOut)方法就是设置超时。
         其实不然,socket设置超时分为两种,上面提到为读写超时。
         第一:建立连接的超时设置,代码如下:

socket.connect(SocketAddress endpoint, int timeout);

         第二:读写超时时间的设置,代码如下:

socket.setSoTimeout(int soTimeOut);

 

 

         socket编程时代码整体编写如下:

String ip="127.0.0.0";
int port="8080";
int connectTimeOut=3000;
int soTimeOut=5000;
InetAddress addr = InetAddress.getByName(ip);
socket = new Socket();
// 设置连接超时时间
socket.connect(new InetSocketAddress(addr, port), connectTimeOut);
// 设置读写超时时间
socket.setSoTimeout(soTimeOut);

        设置超时的时间级别均为毫秒。

        最后,注意socket的异常处理,这里不再赘述。