Start New Discussion within our Software Development Community

Hi all.

I'm trying to create a server/client program in java for an assignment. I'm struggling to get the receiver thread working, which I want to do before I implement the more complex features, but I keep tripping up with the receiver. The sender will send the message, the server can read it, but the receiver thread causes the client program to brick every time with a NPE right on the socket.receive(packet);

public class CReceiveThread  implements Runnable {

    public static final int MAX_PACKET_SIZE = 65507;    


DatagramSocket socket;
InetAddress address;
byte[] buf = new byte[MAX_PACKET_SIZE]; 
String host = "127.0.0.1";     

    @Override
    public void run() {
        // TODO Auto-generated method stub


        // receive request from client
        System.out.println("client: waiting to receive datagram..");
        DatagramPacket packet = new DatagramPacket(buf, buf.length);

        try {
            Thread.sleep(5000);
            socket.receive(packet);
        } catch (IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("client: datagram received..");




        buf = packet.getData();


        String message = new String(packet.getData());
        message = message.trim();
        System.out.println("Message Received from Server:" + message);





    }

You get a null pointer because you have not initialised the variable socket. You seem to be missing the call to create a DatagramSocket and connect that to the server.

This article has been dead for over six months. Start a new discussion instead.