转载:http://androidguy.blog.51cto.com/974126/214445
客户端套接字的超时(timeout)就是指在客户端通过Socket和服务器进行通讯的过程中,由于网络延迟,网络阻塞等原因,造成服务器并未及时响应客户端的一种现象。在一段时间后,客户端由于未收到服务端的响应而抛出一个超时错误;其中客户端所等待的时间就是超时时间。
Socket socket = new Socket();
socket.setSoTimeout(5000);
socket.connect(… …);
socket.getInputStream().read();
package mynet;
import java.net.*;
public class SocketTimeout
{
public static void main(String[] args)
{
long time1 = 0, time2 = 0;
Socket socket = new Socket();
try
{
if (args.length < 4)
{
System.out.println("参数错误!");
return;
}
time1 = System.currentTimeMillis();
socket.connect(new InetSocketAddress(args[0], Integer
.parseInt(args[1])), Integer.parseInt(args[2]));
socket.setSoTimeout(Integer.parseInt(args[3]));
time1 = System.currentTimeMillis();
socket.getInputStream().read();
}
catch (SocketTimeoutException e)
{
if (!socket.isClosed() && socket.isConnected())
System.out.println("读取数据超时!");
else
System.out.println("连接超时");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
finally
{
time2 = System.currentTimeMillis();
System.out.println(time2 - time1);
}
}
}
java mynet.SocketTimeout 192.168.18.24 80 3000 5000
连接超时
3045
java mynet.SocketTimeout www.ptpress.com.cn 8888 3000 5000
连接超时
3075
java mynet.SocketTimeout www.ptpress.com.cn 80 3000 5000
读取数据超时!
5008
java mynet.SocketTimeout www.ptpress.com.cn 80 3000 0
Connection reset
131519