创建基于 Ajax 的 IM 客户端(5)发送消息
 
- UID
- 1066743
|

创建基于 Ajax 的 IM 客户端(5)发送消息
发送消息有了相关的 Chat 对象后,发送信息十分简单(参见清单 5):
清单 5. 发送消息1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| ....
public static void main (String args[]){
ChatBot test = new ChatBot();
test.go();
test.startNew();
test.sendMessage("myFriend@myjabberserver.net", "Hey there!");
}
....
XMPPConnection conn;
public void sendMessage(String targetUser, String theMessage){
Chat theChat = (Chat)chatSessions.get(targetUser);
try {
theChat.sendMessage(theMessage);
} catch (Exception e){
e.printStackTrace();
}
}
private void createConversation(String target){
....
|
这里,向 main() 方法添加了一条语句,告知此对象一旦完成了自身初始化,它就应该发送一条文本消息给 myfriend@myjabberserver.net,地址与之前初始 Chat 所用的相同。发送后,bot 的 sendMessage() 方法就会寻找相关的 Chat 对象 —,记得么,最初是基于地址将其添加到 Hashtable 的。一旦找到了 Chat 对象,它就可以发送消息。
若要测试,可以使用 Spark 登录到发送消息的那个帐号并运行应用程序。应该可以看到弹出一个消息窗口,其上显示文本 “Hey there!”。
接收消息但如果好友回发消息又该如何呢?消息会回到 Chat,然后呢?还不尽然。我们需要告诉 MessageListener 的 processMessage() 方法去处理此事,如清单 6 所示:
清单 6. 接收消息1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| ....
private void createConversation(String target){
try {
chatQueues.put(target, "");
Chat chat = conn.getChatManager().createChat(target,
new MessageListener() {
public void processMessage(Chat chat, Message message) {
try {
chat.sendMessage("Got "+message.getBody());}
catch (Exception e){
e.printStackTrace();
}
String currentQueue = chatQueues.get(chat.getParticipant());
chatQueues.put(chat.getParticipant(), currentQueue
+ "<br />" + message.getBody());
S ystem.out.println(chat.getParticipant() + " said " +
message.getBody());
}
}
);
chatSessions.put(target, chat);
} catch (Exception e){
System.out.println("Create Conversation Exception");
e.printStackTrace();
}
}
....
|
现在,当用户从 Spark(或任何其他客户端)发送消息时,会发生两件事情。首先,检索消息主体 — 他/她究竟说了什么 — 并将其发送回给他/她。当然,这不是正常的会话协议,但它会让您在构建应用程序的时候知道收听者的工作。
第二,基于发出消息的那个用户(“参与者”)从队列检索应用程序的当前文本、向其添加当前消息并将其放回队列。
最后, 同样,还是可以查看其工作、输出一个语句说明所发生的事情。
保存、编译并运行此应用程序。这次,当谈话窗口弹出时,试着将文本发回。应该可以在谈话窗口本身以及 Java 控制台看到这样做的效果。
现在我们需要将此转变成一个 Web 应用程序。 |
|
|
|
|
|