我正在尝试编写一个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();
}
}}}}
答案 0 :(得分:1)
我能看到的第一个问题(除了会停止代码编译的输入错误的变量名称)是套接字超时:如果套接字超时到期,receive
函数将抛出SocketTimeoutException
你的代码无法处理。 receive
does not return a value,因此无法将结果与null
进行比较。相反,你需要做这样的事情:
try {
clientSocket.receive(receivePacket);
sequenceNo++;
... // rest of the success path
} catch (SocketTimeoutException ex) {
clientSocket.send(sendPacket);
}