我正在使用字节数组来存储从另一台计算机接收的数据包。
receivedData = new byte[1024];
receivedPacket = new DatagramPacket(receivedData, receivedData.length);
socket.receive(receivedPacket);
receivedData = receivedPacket.getData();
String res = new String(receivedData); // PROBLEM HERE
问题出在最后一行:因为我将
receivedData
声明为长度为1024的字节流。因此,尽管最后一行并不确切知道我收到了多少个实际字节,但总会从整个数组中创建一个新字符串。因此,我遇到了沮丧的错误:res
没有收到我想要的。 (因为我收到的实际字节的长度无法修复整个数组)因此,我的问题是:我该如何解决这一点,我怎么知道我实际收到的要转换为字符串的字节数?
最佳答案
尝试使用DatagramPacket.getLength()
。
receivedData = new byte[1024];
receivedPacket = new DatagramPacket(receivedData, receivedData.length);
socket.receive(receivedPacket);
receivedData = receivedPacket.getData();
String charsetName = "US-ASCII"; // set to desired charset
String res = new String(receivedData, 0, receivedPacket.getLength(), charsetName);
编辑添加字符集。谢谢,parsifal。