Asmack源碼入門,asmack源碼
Smack的初始化涉及到兩個步驟:
1.初始化系統屬性——通過SmackConfiguration進行系統屬性初始化。這些屬性可以通過getxxx()方法擷取。
2.初始化啟動類——初始化類意味著在啟動時候執行個體化該類,如果繼承SmackInitializer則需要調用initialize()方法。如果不繼承SmackInitializer則初始化的操作必須在靜態代碼塊中,一旦載入類時自動執行。
Establishing a Connection建立串連
XmppTCPConnection類是被用來建立串連到xmpp伺服器的。
// Create a connection to the jabber.org server._
XMPPConnection conn1 = new XMPPTCPConnection("jabber.org");
conn1.connect();
// Create a connection to the jabber.org server on a specific port._
ConnectionConfigurationconfig = new ConnectionConfiguration("jabber.org", 5222);
XMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.connect();
ConectionConfiguration類提供一些控制操作,譬如是否加密。
Working with the Roster 花名冊
Roster可以讓你保持擷取其他使用者的presence狀態,使用者可以添加進組“Friend”或者“Co-workers”,你可以知曉使用者是否線上。
檢索roster可以通過XMPPConnection.getRoster()方法,roster類允許你查看所有的roster enteries ,群組資訊當前的登入狀態。
Reading and WritingPackets讀寫資料包
XMPP伺服器和用戶端間以XML傳遞的資訊被稱為資料包。
org.jivesoftware.smack.packet包內有三種封裝好的基本的packet,分別是message, presence和IQ。
比如Chat和GroupChat類提供了更進階別的結構用以建立發送packet,當然你也可以直接用packet。
// Create a new presence. Pass in false to indicate we're unavailable._
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
// Send the packet (assume we have aXMPPConnection instance called "con").
con.sendPacket(presence);
Smack提供兩種讀取packets
PacketListener和PacketCollector,這兩種都通過PacketFilter進行packet加工。
A packet listener is used for event style programming, while a packet collector has a result queue of packets that you can do polling and blocking operations on.
(packet listener事件監聽,而packet collector是一個packets的可以進行polling和blocking操作的結果集隊列。)
So, a packet listener is useful when you want to take some action whenever a packet happens to come in, while a packet collector is useful when you want to wait for a specific packet to arrive.
(packet listener一旦資料包傳遞抵達的時候你可以進行處理,packet collector則被使用在你需要等待一個指定的packet傳遞抵達時候。)
Packet collectors and listeners can be created using an Connection instance.
(packet listener和packet collector在connection執行個體中被建立。)
// Create a packet filter to listen for new messages from a particular
// user. We use an AndFilter to combine two other filters._
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class),
newFromContainsFilter("mary@jivesoftware.com"));
// Assume we've created a XMPPConnection name "connection".
// First, register a packet collector using the filter we created.
PacketCollectormyCollector = connection.createPacketCollector(filter);
// Normally, you'd do something with the collector, like wait for new packets.
// Next, create a packet listener. We use an anonymous inner class for brevity.
PacketListenermyListener = new PacketListener() {
public void processPacket(Packet packet) {
// Do something with the incoming packet here._
}
};
// Register the listener._
connection.addPacketListener(myListener, filter);
Managing Connection
Connect and disConnect
// Create the configuration for this new connection_
ConnectionConfigurationconfig = new ConnectionConfiguration("jabber.org", 5222);
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
// Connect to the server_
connection.connect();
// Log into the server_
connection.login("username", "password", "SomeResource");
...
// Disconnect from the server_
connection.disconnect();
Messaging using Chat
Chat
org.jivesoftware.smack.Chat
// Assume we've created a XMPPConnection name "connection"._
ChatManagerchatmanager = connection.getChatManager();
Chat newChat = chatmanager.createChat("jsmith@jivesoftware.com", new MessageListener() {
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
newChat.sendMessage("Howdy!");
}
catch (XMPPException e) {
System.out.println("Error Delivering block");
}
Message newMessage = new Message();
newMessage.setBody("Howdy!");
message.setProperty("favoriteColor", "red");
newChat.sendMessage(newMessage);
// Assume a MessageListener we've setup with a chat._
public void processMessage(Chat chat, Message message) {
// Send back the same text the other user sent us._
chat.sendMessage(message.getBody());
}
incoming Chat
_// Assume we've created a XMPPConnection name "connection"._
ChatManagerchatmanager = connection.getChatManager().addChatListener(
newChatManagerListener() {
@Override
public void chatCreated(Chat chat, booleancreatedLocally)
{
if (!createdLocally)
chat.addMessageListener(new MyNewMessageListener());;
}
});
Roster and Presence
roster entries
包含xmpp地址,備忘名,群組(假如該使用者不屬於任何一組,則調用“unfiled entry”):
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
System.out.println(entry);
}
監聽roster和presence更改:
Roster roster = con.getRoster();
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
});
Provider architecture
smack provider是用於解析packet extension 和 IQ xml流的,有兩種類型的provider:
IQProvider -parses IQ request into java objects
Extension Provider - parses XML sub-documents attached to packets into PacketExtension instances. By default, Smack only knows how to process a few standard packets and sub-packets that are in a few namespaces such as:
(解析packet的xml子項目到PacketExtension執行個體中。Smack預設僅知道處理少數的標準packets和少數的指定的namespaces下的子packets)