Java ArrayList不通过套接字更新内容
我有一个典型的多线程服务器和一个客户端,它通过套接字和服务器连接并执行一些操作 客户部分:Java ArrayList不通过套接字更新内容,java,multithreading,sockets,debugging,arraylist,Java,Multithreading,Sockets,Debugging,Arraylist,我有一个典型的多线程服务器和一个客户端,它通过套接字和服务器连接并执行一些操作 客户部分: try { mySocket=new Socket("localhost", 1234); ObjectOutputStream oos= new ObjectOutputStream(mySocket.getOutputStream()); ObjectInputStream ois= new ObjectInputStream(mySocket.getInpu
try {
mySocket=new Socket("localhost", 1234);
ObjectOutputStream oos= new ObjectOutputStream(mySocket.getOutputStream());
ObjectInputStream ois= new ObjectInputStream(mySocket.getInputStream());
try{
while(true){
//Here user is asked for input the protocol string
if("one message".equals(protocol))
{
oos.writeObject(protocol);
oos.flush();
mylist=(ArrayList<MyClass>)ois.readObject();
System.out.println(mylist);
}
if("two message".equals(protocol))
{
//tell server to change few things on the list
}
}//end while
} //end inner try
catch (IOException | ClassNotFoundException ex)
{
// ex.printStackTrace();
}
ois.close();
oos.close();
mySocket.close();
}//end outer try
catch (IOException e)
{
//message
}
问题在于:
if ("one message".equals(protocol))
{
oos.writeObject(list); //sends the wrong (?)
oos.flush();
System.out.println(list); //prints the correct
}
从服务器的角度来看,似乎每次用户更改某些内容时都会打印正确的列表。但是,不管客户机做了多少更改,客户机都会接收并打印第一个列表。如果另一个线程来请求列表,它将获取最新的列表,如果该线程或另一个线程进行了更多更改,服务器仍将每次从其一侧打印正确的列表,但客户端总是会返回错误的列表,即该客户端线程进入时存在的列表 您是序列化流中对象缓存的受害者。第一次写入对象时,将为该引用地址创建对象的缓存版本。然后每次你写它时(即使你更改了内容),它也不会再写,因为它说“我已经在这个地址找到了对象”
解决此问题的最佳方法是将套接字流保持在while循环之外,但将ObjectOutput和ObjectInput流置于while循环之内。这应该能解决你的问题。通常,其中一组是为一个稳定的对象图而设计的。如果您要求ObjectOutputStream发送它已经发送的对象,它只发送对先前发送的对象的引用。这就是允许发送对象的复杂图形的原因,对象之间具有双向引用或循环
如果您希望流忘记它已经发送的内容,那么您需要调用该方法。我爱您,谢谢,它显然有效。另外,一旦使用了reset(),就不需要使用flash()?我只需要重置()而不是flash()就可以了,但是什么是最佳技术呢?如果需要flush(),那么调用flush()。如果需要重置(),则调用reset()。它们做不同的事情,文档中没有说reset()也会刷新流。感谢您的输入,下次我会记住它。
if ("one message".equals(protocol))
{
oos.writeObject(list); //sends the wrong (?)
oos.flush();
System.out.println(list); //prints the correct
}