Asmack source code entry, asmack source code

Source: Internet
Author: User

Asmack source code entry, asmack source code

The initialization of Smack involves two steps:

1. initialize system properties-initialize system properties through SmackConfiguration. These attributes can be obtained through the getxxx () method.

2. initialize the startup class -- the initialization class means to instantiate the class at startup. If the class inherits SmackInitializer, you need to call the initialize () method. If SmackInitializer is not inherited, the initialization operation must be performed in the static code block and automatically executed once the class is loaded.

Establishing a Connection

The XmppTCPConnection class is used to create a connection to the xmpp server.

// 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 ();

The ConectionConfiguration class provides some control operations, such as encryption.

Working with the Roster

Roster allows you to maintain the presence status of other users. You can add the user to the group "Friend" or "Co-workers" to check whether the user is online.

You can use the XMPPConnection. getRoster () method to retrieve roster information. The roster class allows you to view all roster enteries and the current logon status of group information.

Reading and WritingPackets

The information transmitted in XML between the XMPP server and the client is called a data packet.

The org. jivesoftware. smack. packet contains three encapsulated basic packages: message, presence, and IQ.

For example, the Chat and GroupChat classes provide a more advanced structure for creating and sending a packet. Of course, you can also directly use 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 provides two methods to read packets

PacketListener and PacketCollector, both of which are processed by PacketFilter.

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 event listening, while packet collector is a packets result set queue that can perform polling and blocking operations .)

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 can be processed once a packet is delivered, and packet collector is used when you need to wait for a specified packet to be delivered .)

Packet collectors and listeners can be created using an Connection instance.

(Packet listener and packet collector are created in the connection instance .)

// Create a packet filter to listen for new messages from a participant

// 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 brefill.

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

Contains the xmpp address, remark name, and group (if the user does not belong to any group, "unfiled entry" is called "):

Roster roster = connection. getRoster ();

Collection <RosterEntry> entries = roster. getEntries ();

For (RosterEntry entry: entries ){

System. out. println (entry );

}

Listen for roster and presence changes:

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 is used to parse packet extension and IQ xml streams. There are two types of providers:

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:

(Parse the xml child element of packet to the PacketExtension instance. By default, Smack only processes a few standard packages and a few sub packages under the specified namespaces)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.