是Java Networking的新手,我正在尝试使用datagramPacket反序列化通过网络发送的消息。但我得到了不同的东西。以下是代码。
发送代码
public static void main(String[] args) {
try{
String host = "localhost";
InetAddress addr = InetAddress.getByName(host);
NewClass Details = new NewClass("Jay", 1);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream In = new ObjectOutputStream(buffer);
In.writeObject(Details);
In.flush();
byte[] Buf= buffer.toByteArray();
DatagramPacket packet = new DatagramPacket(Buf, Buf.length, addr, 7000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
}catch (Exception error){
error.printStackTrace();
}
}
接收代码
public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(7000);
socket.setSoTimeout(0);
while (true) {
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String message = new String(buffer);
System.out.println(message.trim());
}
} catch (Exception error) {
error.printStackTrace();
}
}
这是打印出来的