简体   繁体   中英

Client can't receive UDP datagram from the server

I'm able to send a UDP datagram from my client to my server and receive it, however I can't send a datagram back to the client from my server.

Nothing happens. All I see is: "Hello Server" on the server side, but I don't see: "Hello Client" on the client side.

    final int PACKETSIZE = 100;

//CLIENT
        byte[] newData = "Hello Server".getBytes();
        DatagramPacket newPacket = new DatagramPacket(newData, newData.length, packet.getAddress(), packet.getPort());

        // Send it
        socket.send(newPacket);

        // Set a receive timeout, 2000 milliseconds
        socket.setSoTimeout(2000);

        // Prepare the packet for receive
        packet.setData(new byte[PACKETSIZE]);

        // Wait for a response from the server
        socket.receive(packet);

        // Print the response
        System.out.println("RECEIVED MESSAGE FROM SERVER: " + new String(packet.getData()));

//SERVER
        int port = Integer.parseInt("1024");
        socket = new DatagramSocket(port);

        System.out.println("SERVER STARTED ON UDP PORT: " + port);


        while (true) {
            // Create a packet
            packet = new DatagramPacket(new byte[PACKETSIZE], PACKETSIZE);

            // Receive a packet (blocking)
            socket.receive(packet);

            // Print the packet sent from the client
            System.out.println(packet.getAddress() + " " + packet.getPort() + ": " + new String(packet.getData()));
            // Create a new packet to send back to the client
            byte[] newData = "Hello Client".getBytes();
            DatagramPacket newPacket = new DatagramPacket(newData, newData.length, packet.getAddress(), packet.getPort());
            // Return the packet to the sender (the client)
            socket.send(newPacket);
        }

Got it working. Was reusing the same packet.

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