我具有以下UDP客户端和servcer类,并且尝试将UDPClient中的某些字符串发送到本地和端口7777的同一java项目中的另一个类'UDPServer'。我遇到的问题是我没有收到UDPClient类中UDPServer类中的所有内容。有谁知道问题出在哪里?

感谢您的帮助!

UDP客户端

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class UDPClient {

    public static void main(String args[]) throws Exception {
        String aString = "Hello World";
        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];
        sendData = aString.getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
        clientSocket.send(sendPacket);
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket);
        String modifiedSentence = new String(receivePacket.getData());
        System.out.println("FROM SERVER:" + modifiedSentence);
        clientSocket.close();
    }
}


UDP服务器

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


class UDPServer {

        public static void main(String args[]) throws Exception {
            DatagramSocket serverSocket = new DatagramSocket(7777);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
            while (true) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                String sentence = new String(receivePacket.getData());
                System.out.println("RECEIVED: " + sentence);
                InetAddress IPAddress = receivePacket.getAddress();
                int port = receivePacket.getPort();
                String capitalizedSentence = sentence.toUpperCase();
                sendData = capitalizedSentence.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
                serverSocket.send(sendPacket);
            }
        }
}

最佳答案

嗨,尝试检查端口分配有什么问题,因为您的代码工作正常。

启动服务器并运行以下命令:

视窗

 netstat -aon | FINDSTR 7777


Linux:

 netstat -aon | grep 7777


您应该看到PID检查pid是否与UDPServer运行时相同。还检查防火墙,也许有什么问题吗?

09-30 18:38