How to get rid of the empty remaining of the buffer?(如何摆脱缓冲区的剩余空间?)
问题描述
我有一个使用数据报套接字交换消息的服务器-客户端应用程序.我最初将缓冲区大小设置为 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 = ("这是另一个数据包.
").getBytes();DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport);socket.send(数据包)
Client code:
byte[] buf = ("This is another packet.
").getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, inetAddress, serverport);
socket.send(packet)
服务器代码:字节[] buf = 新字节[1024];DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);
推荐答案
好的,所以我想出了一个适合我的解决方案:
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?
这篇关于如何摆脱缓冲区的剩余空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何摆脱缓冲区的剩余空间?
基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
