我面临一个关于通过 TCP 套接字发送和接收序列化对象的问题。实际上,我可以在服务器线程和客户端线程之间正确接收/发送对象。但是,问题是如果更改了接收/发送对象的属性值,则等待线程无法实现此更改。考虑这个代码示例;
public class ClientThread extends javax.swing.JFrame implements Runnable {
ClientObject mainClient; // Initiliazed after sockets connect to server successfully
.
.
.
String addNewBuddy = JOptionPane.showInputDialog(this, "Enter the Username of the person who you want to add...");
mainClient.setBuddyRequest(true);
mainClient.setBuddyRequestAccount(addNewBuddy);
send.writeObject(mainClient); // write into an ObjectOutputStream
send.flush(); // flush it
System.out.println("mainClient.setBuddyRequest : " + mainClient.isBuddyRequest() + " setBuddyRequestAccount : " + mainClient.getBuddyRequestAccount()); // Check if values changed properly
ClientObject tempClientObject; // temporary an instance of ClientObject
while(( tempClientObject = (ClientObject) receive.readObject()) != null){
if( !tempClientObject.isBuddyRequest() ){
JOptionPane.showMessageDialog(this, "Buddy Request Information", "Requested buddy doesnt exist!!!", JOptionPane.ERROR_MESSAGE);
break;
}
else{
JOptionPane.showMessageDialog(this, "Buddy Request Information", "Requested buddy added into your buddy list succesfully", JOptionPane.INFORMATION_MESSAGE);
labelSetText = tempClientObject.getNickName();
onlineStatus = tempClientObject.isIsOnline();
model.addElement(createPanel());
}
}
.
.
.
}
因此,在我更改了一些属性后,mainClient
我将其发送到服务器。这是服务器线程等待对象做出反应的部分。此外,当客户端发送第二个对象(使计数器大于 0)时,服务器线程可以毫无错误地读取它,但我认识到即使客户端将修改后的对象作为第二条消息发送到服务器,第一个和第二个对象的属性之间也没有区别! .
while( ( clientO = (ClientObject) receive.readObject()) != null ){
counterMessage++;
if( counterMessage==1) { //
checkAccountIfExist(toWrite,file.exists(),toModify,clientO); // Check is connected account exist in database of server
} // end of if (counter==1)
else{ // Second time when server waits
// prints counter=2 but clientO.isBuddyRequest printed as 'false'
//instead of 'true' so this makes if statement unreachable!
System.out.println("Counter = " + counterMessage + " BUDDYREQUEST : " + clientO.isBuddyRequest() + " USERNAME : " + clientO.getUserName());
if(clientO.isBuddyRequest()){
System.out.println("Entered");
checkBuddyAvalaible(clientO);
}
}
}
最后是我的可序列化 ClientObject 的代码
public class ClientObject implements Serializable {
private static final long serialVersionUID = 8662836292460365873L;
private String userName;
private String password;
private String nickName;
private String message;
private boolean checkAcc;
private LinkedList<ClientObject> buddyList;
private boolean isOnline;
private boolean buddyRequest;
private String buddyRequestAccount;
public ClientObject(String userName, String password){
this.userName = userName;
this.password = password;
this.checkAcc = false;
this.buddyList = new LinkedList<ClientObject>();
this.isOnline = false;
this.buddyRequest = false;
this.buddyRequestAccount = null;
}
...methods of getters and setters
}
我希望我已经清楚这个问题,我会感谢每一个答案,无论如何,谢谢。