Messaging using Chat and GroupChat

Sending messages back and forth is at the core of instant messaging. Two classes aid in sending and receiving messages:

Both the Chat and GroupChat classes use the org.jivesoftware.smack.packet.Message packet class to send messages. In certain circumstances, you may wish to bypass the higher-level Chat and GroupChat classes to send and listen for messages directly.


A chat creates a new thread of messages (using a thread ID) between two users. The following code snippet demonstrates how to create a new Chat with a user and then send them a text message:

// Assume we've created an XMPPConnection name "connection".
Chat newChat = connection.createChat("");

The Chat.sendMessage(String) method is a convenience method that creates a Message object, sets the body using the String parameter, then sends the message. In the case that you wish to set additional values on a Message before sending it, use the Chat.createMessage() and Chat.sendMessage(Message) methods, as in the following code snippet:

// Assume we've created an XMPPConnection name "connection".
Chat newChat = connection.createChat("");
Message newMessage = newChat.createMessage();
message.setProperty("favoriteColor", "red");

The Chat object allows you to easily listen for replies from the other chat participant. The following code snippet is a parrot-bot -- it echoes back everything the other user types.

// Assume we've created an XMPPConnection name "connection".
Chat newChat = connection.createChat("");
newMessage.setBody("Hi, I'm an annoying parrot-bot! Type something back to me.");
while (true) {
    // Wait for the next message the user types to us.
    Message message = newChat.nextMessage();
    // Send back the same text the other user sent us.

The code above uses the Chat.nextMessage() method to get the next message, which will wait indefinitely until another message comes in. There are other methods to wait a specific amount of time for a new message, or you can add a listener that will be notified every time a new message arrives.


A group chat connects to a chat room on a server and allows you to send and receive messages from a group of people. Before you can send or receive messages, you must join the room using a nickname. The following code snippet connects to a chat room and sends a message.

// Assume we've created an XMPPConnection name "connection".
GroupChat newGroupChat = connection.createGroupChat("");
// Join the group chat using the nickname "jsmith".
// Send a message to all the other people in the chat room.

In general, sending and receiving messages in a group chat works very similarly to the Chat class. Method are also provided to get the list of the other users in the room.