我是java的新手,我刚创建了两个使用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时,客户端的输出如下:
插入号码:
6 收到的数字:4
收到的数字:4
收到的数字:4
服务器的输出如下:
听力
收到的数字:6
现在减少到:4
听力
答案 0 :(得分:0)
客户端不断发送相同的号码。您永远不会更新dpSend
。