gpt4 book ai didi

java - UDP 数据报中发送的消息未经过净化?

转载 作者:行者123 更新时间:2023-12-02 03:39:04 25 4
gpt4 key购买 nike

我的代码如下。一切都按照我想要的方式进行,但是当收到我的消息时,它们的末尾有很多框,有点像这样“消息:你好▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀"如何才能让接收和打印的内容仅为“Message: hello”?我非常感谢任何帮助。

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());

常见问题。忽略数据报长度。修复如下:

String sentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());

关于java - UDP 数据报中发送的消息未经过净化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com