UDP接收和发送UDP包的问题?

时间:2011-09-22 10:58:43

标签: java sockets udp datagram

我正在尝试编写一个关于UDP Connections的简单程序来了解它们。我已经实现了一些基本的东西,但是当我尝试发送并取回我发送的内容时,我遇到了一些问题,例如,

当我这样做时; 发送字符串

" ASD"到服务器我得到了asdxxxxxxxxxx 当我尝试打印服务器中的内容时,我得到[B @ 5f186fab

我该如何解决这个问题?

为了更清楚,我发送了几行代码,

在客户端;

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

在服务器中;

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

谢谢大家

编辑1 我认为我的缓冲区有问题,但我不知道如何解决。

2 个答案:

答案 0 :(得分:2)

您可以使用

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

但你可能想要的是

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

答案 1 :(得分:0)

你修好过吗?

否则,我发现如果你声明一个容量大于你实际收到的长度字符串的接收byte[] buf,你最终会得到其余的缓冲区。不需要的字节。

EG。如果你声明byte[] received = new byte[1000];但只接收一个4字节的字符串,你最终会得到996个不需要的字节。

快速解决这个问题的方法是做一些像

这样的事情
byte[] received = packet.getData();
System.out.println(received.toString().trim());

trim()为我做了诀窍。希望对你有帮助!