我的任务是让一个简单的TCP客户端超时。客户端按预期工作,但是当客户端没有收到3秒或更长时间的输入时,我似乎无法让客户端超时。 我对SO_TIMEOUT有基本的了解,但不能在这里工作。 请帮忙
这是我的代码: 的的TcpClient
private static final String host = "localhost";
private static final int serverPort = 22003;
public static void main(String[] args) throws Exception
{
try
{
System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
@SuppressWarnings("resource")
Socket client = new Socket(host, serverPort);
client.setSoTimeout(3000);
while(true)
{
DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
String input = inFromUser.readLine();
outToServer.writeBytes(input + "\n");
String modedInput = inFromServer.readLine();
System.out.println("You Sent: " + modedInput);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println("Slept-in");
e.getStackTrace();
}
}
}
catch(SocketTimeoutException e)
{
System.out.println("Timed Out Waiting for a Response from the Server");
}
}
答案 0 :(得分:1)
setSoTimeout
并不能按照您的想法行事。来自Javadoc:
将此选项设置为非零超时,对()调用read() 与此Socket关联的InputStream将仅阻止此操作 时间量。
从套接字读取超时,即使没有数据,reads()
也会在3秒后返回。它不是套接字不活动的超时 - 即套接字在空闲3秒后不会断开连接。