Asmack Source Code Entry

Source: Internet
Author: User
Tags event listener

The initialization of smack involves two steps:

1. Initialize the System Properties--Initialize the system properties by Smackconfiguration. These properties can be obtained through the GetXXX () method.

2. Initialize the startup class-The initialization class means that the class is instantiated at startup, and the Initialize () method needs to be called if inheriting Smackinitializer. If you do not inherit Smackinitializer, the initialized operation must be in a static code block and executed automatically once the class is loaded.

Establishing a connection creating a connection

The Xmpptcpconnection class is used to create connections 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 whether to encrypt or not.

Working with the Roster roster

Roster allows you to keep the presence status of other users, users can add to the group "Friend" or "co-workers", you can know whether the user is online.

Retrieving roster can be done through the Xmppconnection.getroster () method, the Roster class allows you to view all roster enteries, the current login status of the group information.

Reading and Writingpackets read and write packets

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

The Org.jivesoftware.smack.packet package is packed with three basic packet, namely message, presence and IQ.

For example, the chat and Groupchat classes provide a higher level of structure to create a send packet, and of course you can use packet directly.

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 offers two types of read packets

Packetlistener and Packetcollector, both of which are packet processed through Packetfilter.

A packet listener is used for event style programming and while a packet collector have a result queue of packets that can Do polling and blocking operations on.

(Packet listener event listener, and packet collector is a packets result set queue that can perform polling and blocking operations.) )

So, a packet listener was useful when you want to take some action whenever a packet happens to come in, while a packet col Lector is useful if you want to wait for a specific packet to arrive.

(Packet listener Once packet delivery arrives you can handle it, packet collector is used when you need to wait for a specified packet delivery to arrive. )

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

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

Create a packet filter to listen for new messages from a particular

User. We use a andfilter to combine and other filters._

Packetfilter filter = new Andfilter (new Packettypefilter (Message.class),

Newfromcontainsfilter ("[email protected]");

Assume we ' ve created a xmppconnection name "connection".

First, register a packet collector using the filter we created.

Packetcollectormycollector = Connection.createpacketcollector (filter);

Normally, you're ' d something with the collector, like wait for new packets.

Next, create a packet listener. We use a 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 ("[Email protected]", 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

Include XMPP address, note name, group (if the user does not belong to any group, call "Unfiled entry"):

ROSTER roster = Connection.getroster ();

collection<rosterentry> entries = Roster.getentries ();

for (Rosterentry entry:entries) {

SYSTEM.OUT.PRINTLN (entry);

}

Monitor 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 provider:

Iqprovider-parses IQ request into Java objects

Extension provider-parses XML sub-documents attached to packets into packetextension instances. By default, Smack-knows how to process a few standard packets and sub-packets, is in a few namespaces as:

(Parses packet XML child elements into an packetextension instance.) Smack default only knows to handle a few of the standard packets and a few sub-packets under the specified namespaces)

Asmack Source Code Entry

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.