【发布时间】:2011-12-11 01:08:16
【问题描述】:
这个问题把我逼疯了。这是针对我目前正在开发的非常简单的在线多人游戏。
我目前能够通过 udp 向我的客户发送数据包,而且他们似乎可以正常接收。但是,当我向客户端发送序列化对象并在另一端反序列化时,当我尝试访问所需的值时,我会收到 NullPointerExceptions。我已经验证了对象在服务器端被正确序列化(反序列化并检查数据),所以我 99% 确定我在发送数据包的代码中做错了什么。
下面是从服务器序列化和发送“数据报”对象的代码:
DatagramPacket sendPacket = null;
byte[] buf = null;
//Serialize the datagram object to send as a UDP packet
try {
// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(data);
buf = bos.toByteArray();
out.close();
bos.close();
} catch (IOException e) {
}
try {
sendPacket = new DatagramPacket( buf, buf.length,
InetAddress.getLocalHost(), 4004);
} catch (UnknownHostException e){}
try {
DatagramSocket sendSocket = new DatagramSocket();
sendSocket.send( sendPacket );
changed = true;
}catch (IOException e) {}
被序列化的“数据”对象充满了正确的值;我很确定。
另一个相关的代码块是客户端的接收块:
public Datagram readDatagram() {
byte[] buff = new byte[20000];
DatagramPacket packet = new DatagramPacket(buff, buff.length);
DatagramSocket receiver = null;
try {
receiver = new DatagramSocket(4004);
receiver.receive(packet);
} catch (IOException e) {
System.out.println("ERROR2");
}
Datagram data = null;// = new Datagram();
try {
// Deserialize from a byte array
ByteArrayInputStream bis = new ByteArrayInputStream(buff);
ObjectInput in = new ObjectInputStream(bis);
data = (Datagram) in.readObject();
bis.close();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
System.out.println("ERROR3");
}
for (int i = 0; i < 35; i++) {
System.out.print(data.getLevel()[i]);
}
receiver.close();
return data;
}
当我尝试在此反序列化后读取任何值时,我得到 NullPointerException。如果有人能指出我正确的方向,我会非常高兴。
哦,我现在故意发送到 localHost 只是为了测试一下。我的客户端和服务器都在我的机器上运行。
【问题讨论】:
标签: java serialization client udp