我的任务是让一个简单的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");
}
}
setSoTimeout
不会做你认为它做的事情。来自Javadoc:
将此选项设置为非零超时时,对 与此套接字关联的输入流将仅为此阻止 时间量。
这是从套接字读取的超时,因此即使没有数据reads()
也会在 3 秒后返回。这不是套接字不活动的超时 - 即套接字在空闲 3 秒后不会断开连接。