开发者

Problems with UDP Received and Sent UDP Packages?

I am tryin开发者_运维百科g 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 .


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"));


Have you fixed this?

Otherwise, what I've found is that if you declare a receiving byte[] buf with a capacity that's greater than the length string you're actually receiving, you'll end up with the rest of the buffer full of unwanted bytes.

Eg. if you declare byte[] received = new byte[1000]; but only receive a string of 4 bytes, you'll end up with 996 unwanted bytes.

One quick way around this is to do something like

byte[] received = packet.getData();
System.out.println(received.toString().trim());

trim() did the trick for me. Hope that helps you!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜