我一直在尝试使用TCP发送数据列表时遇到了一些麻烦。我制作了一个较小版本的问题并夸大了一点。对象输入/输出流。如何反复发送更新的相同对象?
CLIENT
public class Client {
DListStorage dl = new DListStorage();
Data d = new Data();
Socket socket;
public Client(){
d.x = 0;
dl.dl.add(d);
try {
socket = new Socket(InetAddress.getLocalHost(), port);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
for(int i = 0; i < 3; i++){
oos.writeObject(dl);
dl.dl.get(0).x++;
System.out.println("Client: " + dl.dl.get(0).x);
}
socket.close();
socket = new Socket(InetAddress.getLocalHost(), port);
oos = new ObjectOutputStream(socket.getOutputStream());
for(int i = 0; i < 3; i++){
oos.writeObject(dl);
dl.dl.get(0).x++;
System.out.println("Client: " + dl.dl.get(0).x);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器
public class NewConnections {
ServerSocket ssocket;
Socket socket;
public NewConnections(){
acceptConnections.start();
}
Thread acceptConnections = new Thread(new Runnable(){
public void run(){
try {
ssocket = new ServerSocket(port, 0, InetAddress.getLocalHost());
socket = ssocket.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
DListStorage dl;
for(int i = 0; i < 3; i++){
dl = (DListStorage)ois.readObject();
System.out.println("Server: " + dl.dl.get(0).x);
}
socket.close();
socket = ssocket.accept();
ois = new ObjectInputStream(socket.getInputStream());
for(int i = 0; i < 3; i++){
dl = (DListStorage)ois.readObject();
System.out.println("Server: " + dl.dl.get(0).x);
}
ssocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
对我来说,结果如下。
Client: 0.0
Client: 1.0
Server: 0.0
Client: 2.0
Server: 0.0
Server: 0.0
Client: 3.0
Client: 4.0
Server: 3.0
Client: 5.0
Server: 3.0
Server: 3.0
数据和数据存储实现Serializable,数据存储包含 public List<Data> dl = new ArrayList<>();
我无法弄清楚,为什么服务器不读浮动X正常。只有在最初的阅读。
感谢
我加'oos.reset()',它的工作,但我真的需要这要尽可能高效。这不会造成很大的开销,打开和关闭流? –