我有一个有多个客户端连接的服务器。每个客户都有一个他们可以控制的身体(玩家),但可能会发生碰撞,因此他们需要查看其他人的身体以了解为什么他们的某些运动受到限制。
我的解决方案是将“世界”对象传递给输入/输出流的对象。然后我使用处理解析和绘制每个身体。这是我得到的错误:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: org.jbox2d.dynamics.World
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at Client.setup(Client.java:30)
at processing.core.PApplet.handleDraw(PApplet.java:2280)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:243)
at processing.core.PApplet.run(PApplet.java:2176)
at java.lang.Thread.run(Unknown Source)
Caused by: java.io.NotSerializableException: org.jbox2d.dynamics.World
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Player.sendWorld(Player.java:57)
at Server.draw(Server.java:54)
at processing.core.PApplet.handleDraw(PApplet.java:2305)
... 3 more
显然 World 在通过套接字传递之前需要被序列化/可序列化。知道我会怎么做吗?我是否需要为每个身体做这些,创建 xml/json 然后传递它而不是简单地发送世界?
服务器输出
public void sendWorld(World world) {
try {
out.writeObject(world);
out.flush(); // or maybe out.reset()
} catch (IOException e) {
e.printStackTrace();
}
}
客户在
try {
bodySocket = new Socket(serverHostname, port);
in = new ObjectInputStream(bodySocket.getInputStream());
Object next = in.readObject();
System.out.println("Getting world");
if (next instanceof World) {
this.world = (World) next;
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ serverHostname);
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
客户抽奖
public void draw() {
// Background
background(100);
// Bodies (includes floors, walls, and players)
for (Body body = world.getBodyList(); body != null; body = body
.getNext()) {
Vec2 playerLoc = body.getPosition();
rectMode(PApplet.RADIUS);
fill(255, 100);
rect(playerLoc.x, fieldBottom - playerLoc.y, 10, 10);
}
}