gpt4 book ai didi

Java TCP : How to abort/stop the receiver from waiting for sender data after timeout

转载 作者:行者123 更新时间:2023-12-01 05:08:06 29 4
gpt4 key购买 nike

我必须编写java代码来实现TCP服务器和TCP客户端,其中10%的传输失败由随机数确定。现在,在接收方,如果在这 2 秒内没有从发送方收到数据,则需要等待 2000 毫秒(2 秒)。然后它将停止等待来自发送方的数据并向发送方发送回否定的 ACK。

BufferedReader inFromSender =new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
long startTime = System.currentTimeMillis();
while(( System.currentTimeMillis() - startTime) < 2000 )
{
clientSentence = inFromSender.readLine();
System.out.println("Received: " + clientSentence);
}
System.out.println("Data Transmission failed");

但是一旦 while 循环开始并且接收者进入从发送者那里读取数据,它就永远不会中断..即使 2 秒。超时已结束。如何在 2 秒(超时)后中止/停止接收方等待发送方数据。

最佳答案

一种方法是使用一个线程,在达到超时时关闭套接字。这将使 read(...) 调用失败(可能是 IOException),因此您将退出循环。

示例:

final Socket connectionSocket = new Socket("...", 8888); // To be changed
BufferedReader inFromSender = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
Thread t = new Thread() {
public void run() {
try {
Thread.sleep(2000); // Wait 2 s
connectionSocket.close();
System.out.println("Data Transmission failed");
} catch(InterruptedException e) {
// Handle exception
}
}
};
t.start();
while((clientSentence = inFromSender.readLine()) != null) {
System.out.println("Received: " + clientSentence);
}

关于Java TCP : How to abort/stop the receiver from waiting for sender data after timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12437898/

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