Just keep track of the last person to send you a message and respond to that person. That is how I do exactly what you describe.
Here is some code I use (don’'t seem to have code tags available or anything, so sorry about the formatting). lastSender is populated with the getFrom() method of the Message object everytime I receive a message:
private void sendMessage(String message) {
//On the very first message this will be false so this will result in a new Chat object being
//created…and then it will use the same Chat object until the code sees that the sender
//has changed…then it will create a new Chat object with the new sender as the recipient
//of messages the agent sends
if (lastSender.equals(lastRecipient)) {
//We are still talking to the same person, so just send the message on the current
//chatSession
try {
this.chatSession.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
} else {
//Talking to someone new so create a chat session to this new (or initial) person
this.chatSession = new Chat(this.chatConnection, this.lastSender);
this.lastRecipient = this.lastSender;
try {
this.chatSession.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
this.addOutgoingMessageToTextArea(message);
}
Of course this code fails if both user2 and user3 sends a message to user1 at the same time, or if user3 would send a message before you respond to user2 (it is a race condition and can’'t really guarantee who gets the response). However, if you are worried about that you use case you should probably have a chat dialog for each party that user1 is talking to.
In my particular use case I can have a person get a message from someone new at a later time but never have two people talking to one person at the same time.