Search code examples
javasocketsudpdatagram

Problems with UDP Received and Sent UDP Packages?


I am trying to write a simple program about UDP Connections to learn about them. I have implemented some basic things but when I try to send and get back what I sent but I face some problems like,

When I do this ; send a string

"asd" to server I get back asdxxxxxxxxxx and when I try to print What I get in the server I get [B@5f186fab

How can I solve this problem ?

To be more clear I am sending you a few lines of code ,

In client;

Scanner in = new Scanner(System.in);
    String result = in.nextLine();
        // send request
    byte[] buf = new byte[1000];
    String read = result;
    InetAddress address = InetAddress.getByName("localhost");
    DatagramPacket packet = new DatagramPacket(result.getBytes(),  result.getBytes().length, address, 4445);
    socket.send(packet);

        // get response
    packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);

    // display response
    String received = new String(packet.getData(), 0, packet.getLength());
    System.out.println("Quote of the Moment: " + received);

In server ;

            byte[] buf = new byte[1000];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            socket.receive(packet);
            byte[] received = packet.getData();
            System.out.println(received.toString());

                // figure out response

        // send the response to the client at "address" and "port"
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            packet = new DatagramPacket(received, received.length, address, port);
            socket.send(packet);

Thank you all

EDIT 1 I think I have problems with my buffer but I dont know how to solve .


Solution

  • You can use

    System.out.println(Arrays.toString(received));
    

    but what you probably want is

    System.out.println(new String(received, o, lengthRead, "UTF-8"));