0
我的客戶端類中有一個TestEllipse
對象,它擴展Ellipse2D.Double
並將其發送到服務器。服務器調用其updatePosition
方法,將其包裝在ArrayList中,並將ArrayList發送給客戶端。 updatePosition
在橢圓的x座標上加10。客戶端中未反映服務器中對象的更改
奇怪的是,即使updatePosition
被調用,當客戶端接收到ArrayList中的橢圓時,其位置的x座標似乎沒有改變。更新後的位置顯示在服務器...
[TestEllipse[x=60,y=250]]
[TestEllipse[x=70,y=250]]
[TestEllipse[x=80,y=250]]
[TestEllipse[x=90,y=250]]
[TestEllipse[x=100,y=250]]
...而不是在客戶端:
[TestEllipse[x=60,y=250]]
[TestEllipse[x=60,y=250]]
[TestEllipse[x=60,y=250]]
[TestEllipse[x=60,y=250]]
[TestEllipse[x=60,y=250]]
爲什麼會這樣,我怎麼能獲得更新的位置顯示在客戶端?
在服務器端:
import java.awt.geom.Ellipse2D;
import java.io.*;
import java.net.*;
import java.util.*;
public class TestServer {
public static void main(String[] args) {
try {
List<TestClient.TestEllipse> list = new ArrayList<TestClient.TestEllipse>();
ServerSocket listener = new ServerSocket(31362);
Socket socket = listener.accept();
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
try {
TestClient.TestEllipse e = (TestClient.TestEllipse) ois.readObject();
if (e != null)
list.add(e);
for (TestClient.TestEllipse ellipse : list)
ellipse.updatePosition();
// System.out.println(list);
oos.writeObject(list);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
而且在客戶端:
import java.awt.geom.Ellipse2D;
import java.io.*;
import java.net.Socket;
import java.util.*;
public class TestClient {
public static void main(String[] args) {
try {
List<TestEllipse> list = new ArrayList<TestEllipse>();
TestEllipse t = new TestEllipse(50, 250);
Socket socket = new Socket("localhost", 31362);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
try {
oos.writeObject(t);
t = null;
list = (List<TestEllipse>) ois.readObject();
// System.out.println(list);
Thread.sleep(500);
} catch (ClassNotFoundException | InterruptedException ex) {
ex.printStackTrace();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static class TestEllipse extends Ellipse2D.Double {
int x, y;
public TestEllipse(int x, int y) {
super(x,y,10,10);
this.x = x;
this.y = y;
}
public void updatePosition() {
x += 10;
}
@Override
public String toString() {
return "TestEllipse[x="+x+",y="+y+"]";
}
}
}
謝謝!這正是我正在尋找的。 – TNT