gpt4 book ai didi

java - 停止并等待 UDP 服务器

转载 作者:行者123 更新时间:2023-12-01 15:54:33 25 4
gpt4 key购买 nike

我正在尝试编写一个 Java 停止等待 UDP 服务器,我已经完成了该服务器的工作,但我不确定下一步该去哪里。我希望客户端向服务器发送一条消息,设置超时,等待响应,如果没有得到响应,则重新发送数据包,如果得到响应,则增加序列号。直到达到十并继续与服务器发送和接收消息。

我已经走到这一步了,我该如何解决这个问题? :

import java.io.*;
import java.net.*;

public class Client {
public static void main(String args[]) throws Exception {

byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
InetAddress IPAddress = null;

try {
IPAddress = InetAddress.getByName("localhost");
} catch (UnknownHostException exception) {
System.err.println(exception);
}

//Create a datagram socket object
DatagramSocket clientSocket = new DatagramSocket();
while(true) {
String sequenceNo = "0";
sendData = sequenceNo.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 6789);
clientSocket.send(sendPacket);
clientSocket.setSoTimeout(1);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
if(clientSocket.receive(receivePacket)==null)
{
clientSocet.send(sendPacket);
}else { //message sent and acknowledgement received
sequenceNo++; //increment sequence no.
//Create a new datagram packet to get the response
String modifiedSentence = sequenceNo;
//Print the data on the screen
System.out.println("From : " + modifiedSentence);
//Close the socket
if(sequenceNo >= 10 ) {
clientSocket.close();
}
}}}}

最佳答案

我看到的第一个问题(除了会停止代码编译的错误变量名之外)是套接字超时:如果套接字超时到期,receive 函数将抛出 您的代码无法处理的 SocketTimeoutExceptionreceive does not return a value ,因此结果无法与 null 进行比较。相反,您需要执行以下操作:

try {
clientSocket.receive(receivePacket);
sequenceNo++;
... // rest of the success path
} catch (SocketTimeoutException ex) {
clientSocket.send(sendPacket);
}

关于java - 停止并等待 UDP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5345586/

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