我有一個服務器,有幾個客戶端連接。每個客戶都有一個他們可以控制的身體(球員),但可能會發生碰撞,因此他們需要看到其他人的身體知道爲什麼他們的一些動作受到限制。如何序列化JBox2d World對象?
我的解決方案是通過對象輸入/輸出流傳遞「世界」對象。然後我使用處理來解析和繪製每個物體。這裏是我得到的錯誤:
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
顯然世界需要序列化/序列化之前,它可以通過套接字傳遞。任何想法我會怎麼做?我需要爲每個身體做些什麼,創建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);
}
}
如果我不能算出這個很快,我可能最終會通過世界機構名單迭代並創建一個JSON對象持有用戶數據,座標和每個主體的對象類型。將更有效的網絡,但不容易寫。 –