【发布时间】:2014-05-27 12:28:49
【问题描述】:
我有一个典型的多线程服务器和一个通过套接字与服务器连接并执行一些操作的客户端。
客户端部分:
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
}
和服务器端:
public void run() {
try{
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
String protocol;
try{
while(true)
{
protocol= (String)ois.readObject();
if ("one message".equals(protocol))
{
oos.writeObject(list);
oos.flush();
System.out.println(list);
}
if ("two message".equals(protocol))
{
//change objects in the list
}
} //end while true
} //end try
catch (IOException | ClassNotFoundException ex)
{
// ex.printStackTrace();
}
ois.close();
oos.close();
socket.close();
}
catch (Exception ex)
{
//ex.printStackTrace();
}
}
有问题的部分在这里:
if ("one message".equals(protocol))
{
oos.writeObject(list); //sends the wrong (?)
oos.flush();
System.out.println(list); //prints the correct
}
服务器似乎每次用户更改某些内容时都会打印正确的列表。但是随后,无论客户端进行多少更改,客户端都会接收并打印第一个列表。如果另一个线程来询问列表,它将获取最新列表,如果该线程或另一个线程进行更多更改,服务器仍将每次从其一侧打印正确的列表,但客户端总是会返回错误的列表,即该客户端线程进入时存在的列表。
【问题讨论】:
标签: java multithreading sockets debugging arraylist