gpt4 book ai didi

java - TCP 服务器响应超时

转载 作者:可可西里 更新时间:2023-11-01 02:42:41 25 4
gpt4 key购买 nike

我的任务是让一个简单的 TCP 客户端超时。客户端按预期工作,但是当客户端在 3 秒或更长时间内未收到输入时,我似乎无法让客户端超时。我对 SO_TIMEOUT 有基本的了解,但不能让它在这里工作。请帮忙

这是我的代码:TCP客户端

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 :

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.

这是从套接字读取超时,所以即使没有数据,reads() 也会在 3 秒后返回。这不是套接字不活动超时 - 即套接字在空闲 3 秒后不会断开连接。

关于java - TCP 服务器响应超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com