DatagramPacket为字符串 [英] DatagramPacket to string

查看:184
本文介绍了DatagramPacket为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将收到的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())

这篇关于DatagramPacket为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆