2009年3月30日星期一

Smack

昨晚被Smack的example郁闷了,误以为MessageListener是用来返回对方的回复信息,今天终于搞明白了。
Smack是XMPP的一个Java客户端library,可以用来实现Instance Message Tool(Spark、Sparkweb)。服务器端也有相应的的实现,叫Op
enfire,当然,这里只对这两个XMPP的实现讨论,还有很多其他开源实现。顺便提一下,和Smack对应的有个XIFF的Flash客户端实现。

贴一个例子,假设首先启动了Openfire服务器,用Spark客户端登录了某个账户prc,然后在代码中用另一个用户登录,并进行交谈。

效果图:



package org.prc;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
* Chat prototype using smack as client library. Server side are supported by
* openfire.
*
* @author promise
* @date 2009-3-30
*
*/
public class FireChat {
public static XMPPConnection con;
public static Chat newChat;
public static ChatManager chatmanager;

public static void main(String[] args) throws InterruptedException {
// XMPPConnection.DEBUG_ENABLED = true;
try {
// Create a connection to server
ConnectionConfiguration config = new ConnectionConfiguration(
"localhost", 5222);
con = new XMPPConnection(config);

// connect and login with the username and pwd on server
con.connect();
con.login("promise", "promise");
System.out.println("Authenticated = " + con.isAuthenticated());

// add a listener to receive all messages
addListener();

chatmanager = con.getChatManager();
newChat = chatmanager.createChat("prc@fantasy-promise/spark",
new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("I'm sending: "
+ message.getBody());
}
});
newChat.sendMessage("hi");
} catch (XMPPException e) {
e.printStackTrace();
} finally {
Thread.sleep(3600000);
con.disconnect();
}
}

private static void addListener() {
// just need Messages :)
PacketFilter filterMessage = new PacketTypeFilter(Message.class);

PacketListener myListener = new PacketListener() {
public void processPacket(Packet packet) {
System.out.println("From: " + packet.getFrom() + "\n");
System.out.println("Body: " + ((Message) packet).getBody());
// when receiving prc's Message, just say something else again
// and again, robot :)
try {
newChat.sendMessage("hi again :)");
} catch (XMPPException e) {
e.printStackTrace();
}
}
};
// register the listener to the connection
con.addPacketListener(myListener, filterMessage);
}
}

2 条评论:

酸雨 说...

这个和上次讲的教育信息化之类的问题有关系?

promise 说...

无关,偶然看到而已