问题描述
我有一个服务器客户端应用程序,它使用数据报套接字来交换消息。我最初将缓冲区大小设置为1024字节,因为我不知道消息的长度。当我发送短于1024字节的内容时,我将其余的字符串显示为一些奇怪的字符(空字符或我不确定它们是如何被调用的)。
这是一个屏幕:
I have a server-client application that is using a datagram socket to exchange messages. I have initially set the buffer size to be 1024 bytes because I dont know the length of the messages. When I send something that is shorter than 1024 bytes I get the rest of my string displayed as some weird characters (null characters or I am not sure how they are called).Here is a screen:
客户代码:
byte [] buf =(这是另一个数据包。\ n)。getBytes();
DatagramPacket packet = new DatagramPacket(buf,buf.length,inetAddress,serverport);
socket.send(包)
服务器代码:
byte [] buf =新字节[1024];
DatagramPacket packet = new DatagramPacket(buf,buf.length);
socket.receive(包);
推荐答案
好的,我想出了一个对我有用的解决方案:
Ok so I came up with a solution that worked for me:
public String getRidOfAnnoyingChar(DatagramPacket packet){
String result = new String(packet.getData());
char[] annoyingchar = new char[1];
char[] charresult = result.toCharArray();
result = "";
for(int i=0;i<charresult.length;i++){
if(charresult[i]==annoyingchar[0]){
break;
}
result+=charresult[i];
}
return result;
}
编辑:
存在使用 ByteArrayOutputStream
的更好的解决方案可以在这里找到:
There exists a better solution using ByteArrayOutputStream
which can be found here: How to reinitialize the buffer of a packet?
这篇关于如何摆脱剩余的缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!