问题描述
尝试将接收到的 DatagramPacket 转换为字符串,但我有一个小问题.不知道最好的方法是什么.
Trying to convert a received DatagramPacket to string, but I have a small problem. Not sure what's the best way to go about it.
我将要接收的数据大部分长度未知,因此我在接收端设置了一些缓冲区 [1024].问题是,假设我发送了字符串abc",然后在接收端执行以下操作...
The data I'll be receiving is mostly of unknown length, hence I have some buffer[1024] set on my receiving side. The problem is, suppose I sent string "abc" and the do the following on my receiver side...
buffer = new byte[1024];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
buffer = packet.getData();
System.out.println("Received: "+new String(buffer));
我得到以下输出:abc[][][][]][][][]..... 一直到缓冲区长度.我猜最后所有的垃圾/空值都应该被忽略,所以我一定是做错了什么."我知道 buffer.length 是问题所在,因为如果我将其更改为 3(对于此示例),我的出来就好了.
I get the following output: abc[][][][]][][][]..... all the way to the buffer length.I'm guessing all the junk/null at the end should've been ignored, so I must be doing something wrong." I know the buffer.length is the problem because if I change it to 3 (for this example), my out comes out just fine.
谢谢.
推荐答案
new String(buffer, 0, packet.getLength())
这篇关于数据报分组到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!