有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java仅获取相同的udp数据包

我是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时,客户端的输出如下所示:

插入编号:

六, 收到的数目:4

收到的数目:4

收到的数目:4

服务器的输出如下所示:

倾听

收到人数:6

人数现在减少到:4人

倾听


共 (1) 个答案

  1. # 1 楼答案

    客户端一直发送相同的号码。您从不更新dpSend