Getting Started With Smack

This document will introduce you to the Smack API and provide an overview of important classes and concepts.

Requirements

The only requirement for Smack is JDK 1.2 or later. An XML parser is embedded in the smack.jar file and no other third party libraries are required.

Establishing a Connection

The XMPPConnection class is used to create a connection to an XMPP server. To create an SSL connection, use the SSLXMPPConnection class. Below are code examples for making a connection:

// Create a connection to the jabber.org server.
XMPPConnection conn1 = new XMPPConnection("jabber.org");

// Create a connection to the jabber.org server on a specific port.
XMPPConnection conn2 = new XMPPConnection("jabber.org", 5222);

// Create an SSL connection to jabber.org.
XMPPConnection connection = new SSLXMPPConnection("jabber.org"); 

Once you've created a connection, you should login using a username and password with the XMPPConnection.login(String username, String password) method. Once you've logged in, you can being chatting with other users by creating new Chat or GroupChat objects.

Working with the Roster

CONTENT COMING SOON

Packets, the PacketReader, and the PacketWriter

Each message to the XMPP server from a client is called a packet and is sent as XML. The org.jivesoftware.smack.packet package contains classes that encapsulate the different packet types allowed by XMPP (message, presence, and IQ). Classes such as Chat and GroupChat provide higher-level constructs that manage creating and sending packets automatically, but you can also create and send packets directly. Below is a code example for changing the presence to let people we're unavailable because we're out fishing:

// Create a new presence. Pass in false to indicate we're unavailable.
Presence presence = new Presence(false);
presence.setStatus("Gone fishing");
// Send the packet (assume we have a XMPPConnection instance called "con").
con.getPacketWriter().sendPacket(presence);

Every connection has a PacketReader and PacketWriter. The packet reader listens for XML data from the server and parses it into individual packets. You can listen for incoming packets by registering PacketWatcher objects with the packet reader. The packet writer is responsible for writing packets to the server. It takes Packet objects and converts them to XML before sending them over the network.