Jash Jacob
Jash Jacob

Reputation: 580

Receiving Datagram packets are not displayed

I was trying to make a small java program which writes a text message from server to client using DatagramServer and DatagramPacket.

This is the code i've written on the server and client portion.

serverm.java

byte b[] = new byte[1200];
    System.out.println("Enter some text");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String inputMessage = br.readLine();
    b = inputMessage.getBytes();

    DatagramSocket d = new DatagramSocket(6125);
    DatagramPacket p = new DatagramPacket(b,i,InetAddress.getLocalHost(),5461);
    d.send(p);

clientm.java

byte b[] = new byte[1024];
    try
    {
        DatagramSocket d = new DatagramSocket(5461);
        DatagramPacket p = new DatagramPacket(b,1024);
        d.receive(p);

        String outputMessage = new String(p.getData(),0,p.getLength());
        System.out.println(outputMessage);
    }

When running the java program, it runs when the server sends a message to the client - the received message only prints empty line. How can i get the string to be displayed ?

Upvotes: 0

Views: 60

Answers (1)

Ben Minton
Ben Minton

Reputation: 118

I was able to reproduce your problem when I set the 'i' variable in your server to 0.

Make sure that value is the length of the packet you're sending.

Upvotes: 1

Related Questions