Java DatagramSocket不接收数据

时间:2019-03-05 09:37:53

标签: java networking udp

我正在用Java语言编写一个简单的客户端/服务器,但遇到了无法解决的问题。     我在客户端和服务器上都使用DatagramSocket,但是我的服务器无法接收任何数据。我没有收到任何错误,但是那是行不通的。

这是我的服务器源代码:

public class GameServer {

    public static final String serverBuild = "0.00 (050319.milestone0-main)";
    public static final String protocolBuild = "1";

    public DatagramSocket serverSocket;

    public boolean isRunning = false;
    public Thread clientHandler;

    public GameServer(int port, String serverName) {
        System.out.println("Server> Starting a server on port: " + port + ".");
        System.out.println("Server> " + serverName + " running on server build " + serverBuild + ".");
        System.out.println("Server> Using protocol ID: " + protocolBuild + ".");

        isRunning = true;
        try {
            serverSocket = new DatagramSocket(port);
        }catch(Exception ex) {
            System.out.print("Server> ");
            ex.printStackTrace();
        }

        clientHandler();
    }

    public void clientHandler() {
        clientHandler = new Thread(new Runnable() {

            public void run() {

                while(isRunning) {
                    byte[] buffer = new byte[256];
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                    try {
                        serverSocket.receive(packet);
                        System.out.println("Server> " + new String(packet.getData(), 0, packet.getData().length));

                    } catch (IOException e) {
                        System.out.print("Server> ");
                        e.printStackTrace();
                    }

                }

            }

        });
        clientHandler.start();
    }

}

这是我的客户端源代码:

    public class GameClient {

    public GameClient() {

        try {

            DatagramSocket socket = new DatagramSocket(25567);
            byte[] buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.0.24"), 25567);
            socket.send(packet);

        }catch(Exception ex) {
            ex.printStackTrace();
        }

    }

}

客户端非常简单,因为我一直在寻找服务器无法正常工作的原因。

1 个答案:

答案 0 :(得分:-1)

控制台不会打印任何内容,因为客户端发送的软件包是一个空数组。服务器正常工作。