Message sent in UDP datagram is not sanitized?(在 UDP 数据报中发送的消息没有被清理?)
问题描述
我的代码如下.一切都按照我想要的方式进行,但是当收到我的消息时,它们最后会有很多框,有点像这样消息:你好▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀" 我怎样才能使它接收和打印的只是消息:你好"?我非常感谢任何帮助.
My code is as follows. Everything works the way I want it to, but when my messages are received they have many boxes on the end somewhat like this like this "Message: hello▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀" How can I make it so what is received and printed is only "Message: hello"? I greatly appreciate any help.
import java.io.*;
import java.net.*;
public class UDPChat {
public static void main(String args[]) throws Exception {
new UDPChat();
}
public UDPChat() {
try {
runChat();
} catch (Exception e) {
}}
public void runChat() throws InterruptedException {
Sender sender = new Sender();
Receiver receiver = new Receiver();
sender.start();
receiver.start();
sender.join();
receiver.join();
}
class Receiver extends Thread {
public void run() {
try {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
System.out.println("Message: " + sentence);
}
} catch (IOException e) {
}
}
}
class Sender extends Thread {
public void run() {
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
while (true) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
String message = inFromUser.readLine();
sendData = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
}
} catch (IOException e) {
}
}
}
}
推荐答案
String sentence = new String(receivePacket.getData());
常见问题.忽略数据报长度.修复如下:
Usual problem. Ignoring the datagram length. Fix as follows:
String sentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
这篇关于在 UDP 数据报中发送的消息没有被清理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 UDP 数据报中发送的消息没有被清理?
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01