及时通讯的核心是收发信息。Smack提供两个类Chat、GroupChat来完成这项工作。
- # org.jivesoftware.smack.Chat -- 两人交谈
- # org.jivesoftware.smack.GroupChat -- 加入聊天室同多个人进行交谈
Chat
一个Chat在两个用户之间创造一个新的消息线程。下面的代码段说明了如何进行创建Chat,并发送消息
// Assume we've created an XMPPConnection name "connection".Chat.sendMessage(String)方法是一个快捷方法:它首先创建一个Message对象,然后设置消息体,最后发送消息。如果你想在发送消息前增加其他熟悉,你可以使用如下的代码段:
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
newChat.sendMessage("Howdy!");
// Assume we've created an XMPPConnection name "connection".Chat允许你很容易的侦听对方的回复。下面的代码段是一个应声虫,它回显对方输入的信息
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
Message newMessage = newChat.createMessage();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
// Assume we've created an XMPPConnection name "connection".
Chat newChat = connection.createChat("jsmith@jivesoftware.com");
newMessage.setBody("Hi, I'm an annoying parrot-bot! Type something back to me.");
while (true) {
// Wait for the next message the user types to us.
Message message = newChat.nextMessage();
// Send back the same text the other user sent us.
newChat.sendMessage(message.getBody());
使用Chat.nextMessage()方法来获取下一个Message,它会无限期的等,直到有下一个消息。还有别的方法可以为新消息指定一段特定的事件,也可以使用事件驱动模式,当消息来时通知你。
GroupChat
群组聊天允许你连接到聊天室,你可以和组内的人进行通信。在发送和接受消息前,你必须使用一个组名(昵称)来加入某个组。下面的代码段说明了如何加入组并发送消息:
一般来说,在组内收发消息和两人对话类似。并且提供了列出组内其他人的方法。// Assume we've created an XMPPConnection name "connection".
GroupChat newGroupChat = connection.createGroupChat("test@jivesoftware.com");
// Join the group chat using the nickname "jsmith".
newGroupChat.join("jsmith");
// Send a message to all the other people in the chat room.
newGroupChat.sendMessage("Howdy!");
我的标签: Gtalk, Smack, Java
--
爱别人,爱自己!
Very cool design! Useful information. Go on!
ReplyDelete» » »