欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Asmack源码入门

程序员文章站 2024-01-05 13:01:04
...

Smack的初始化涉及到两个步骤: 1.初始化系统属性——通过SmackConfiguration进行系统属性初始化。这些属性可以通过getxxx()方法获

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 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 addresses) {}

public void entriesDeleted(Collection addresses) {}

public void entriesUpdated(Collection 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)