【发布时间】:2014-02-24 15:55:44
【问题描述】:
我在尝试使用 TCP 发送数据列表时遇到了一些麻烦。我把这个问题做了一个更小的版本,并稍微夸大了一点。
客户
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
Data 和 DataStorage 都实现了 Serializable,DataStorage 包含
public List<Data> dl = new ArrayList<>();
我无法弄清楚为什么服务器没有正确读取 float x。仅在初次阅读时。
谢谢
【问题讨论】:
-
我添加了
oos.reset(),它正在工作,但我真的需要它尽可能高效。这不会导致大量开销,打开和关闭流吗?
标签: java list networking arraylist io