我是Java的新手,我刚刚创建了2个使用UDP数据包(客户端和服务器)的程序。客户端从用户那里获取一个整数,并将该数字发送到服务器。然后,服务器从整数中减去2,并将其发送回客户端。消息将来回传递,直到客户端从服务器收到一个非正数。问题是我一直收到相同的号码。有谁知道如何解决这个问题?我需要几个循环吗?
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Scanner;
public class Client {
public static void main (String[] args) throws IOException{
DatagramSocket ds = new DatagramSocket();
System.out.println("Insert number: ");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
int port = 1999;
byte[] byteSend = ByteBuffer.allocate(4).putInt(num).array();
InetAddress address = InetAddress.getByName("localhost");
byte[] byteReceive = new byte[4];
DatagramPacket dpReceive = new DatagramPacket(byteReceive, byteReceive.length);
DatagramPacket dpSend = new DatagramPacket(byteSend, byteSend.length, address, port);
if(num <=0){
ds.close();
}else{
for(int i = 0; i<=num; i+= 2){
ds.send(dpSend);
ds.receive(dpReceive);
num = ByteBuffer.wrap(byteReceive).getInt();
System.out.println("number received: " + num);
}
}
ds.close();
}
}
服务器等级
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;public class Server {
public static void main(String[] args) throws Exception {
DatagramSocket dg = new DatagramSocket(1999);
while(true) {
System.out.println("Listening");
byte[] byteReceive = new byte[4];
DatagramPacket dp = new DatagramPacket(byteReceive, byteReceive.length);
dg.receive(dp);
int num = ByteBuffer.wrap(dp.getData()).getInt();
InetAddress address = dp.getAddress();
int port = dp.getPort();
int numResult = num - 2;
byte[] byteSend = ByteBuffer.allocate(4).putInt(numResult).array();
DatagramPacket dpSend = new DatagramPacket(byteSend, byteSend.length, address, port);
System.out.println("number received: " + num);
System.out.println("number now decreased to: " + numResult);
dg.send(dpSend);
}
}
}
输入6时,Client的输出如下:
插入号码:
6
收到的数量:4
收到的数量:4
收到的数量:4
服务器的输出如下:
倾听
收到的号码:6
现在数量减少到:4
倾听
最佳答案
客户端不断发送相同的号码。您永远不会更新dpSend
。