0
我的代碼如下。一切都按我想要的方式工作,但是當收到我的消息時,他們有許多方框就像這樣:「Message:hello▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀「我怎樣才能做到這一點,所以接收和打印的內容只是」消息:你好「?我非常感謝任何幫助。UDP數據報中發送的消息沒有被消毒?
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) {
}
}
}
}
很好,那正是我一直在尋找的!謝謝您的幫助! – Auborey
@Auborey - 如果它適合你,請接受答案。瞭解如何接受答案---> http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –