我是多线程的新手。我试图在客户端和服务器之间发送消息。当我向服务器发送消息时,服务器中的输出应该是“Aji Computer:Thanks!:D”,但我得到的是截断数据“Aji Computer:Thank”。
服务器代码
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
in.close();
socket.receive(packet);
String dString = "Wassup " + packet.getAddress().getHostName() + "!";
//if (in == null) dString = new Date().toString();
//else dString = getNextQuote();
buf = dString.getBytes();
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
//THIS IS WHERE IM SUPPOSE TO PRINT "Aji Computer: Thanks! :D". But it prints out wrongly
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println(received);
socket.close();
客户端代码
DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName("Aji Computer");
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Server: " + received);
//THIS IS WHERE I SENT MY "Aji Computer: Thanks! :D" PACKET TO SERVER.
buf = new byte[256];
String str = "Aji Computer: Thanks! :D";
buf = str.getBytes();
packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
socket.close();
}
只是为了通知您,此代码来自Oracle。我修改了一下,以便我知道它是如何工作的。
答案 0 :(得分:1)
您将字节数组的大小从256个字节重新分配到:buf = dString.getBytes();
然后在程序中向下创建一个新的数据包,以便在使用packet = new DatagramPacket(buf, buf.length);
时接收它使用{{1}的长度}而不是dString.getBytes()
我假设byte[256]
的空间小于“Aji计算机:谢谢!”
尝试将字节数组重新分配给原始值:
dString.getBytes()
编辑:从上方删除了'byte'