简体   繁体   中英

Java DatagramSocket doesn't receive data

I'm writing a simple client / server in java and I got this problem that I cannot fix. I'm using DatagramSocket on both client and server and my server just cannot receive any data. I don't get any errors but it just doesn't work.

Here is my source code for server:

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();
    }

}

Here is my source code for client:

    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();
        }

    }

}

Client is very simple because I was looking why my server doesn't work.

The console does not print anything, because the client sends the package is an empty array. The server is work right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM