Sending and receiving message using Java Smack API not working on example

15,687

Solution 1

@Flame_Phoenix your sample code is working, I checked with my ejabberd server. I modified the code

Make sure that you added these libraries

  • httpclient-4.1.3.jar
  • httpcore-4.1.4.jar
  • jstun.jar
  • xpp3-1.1.4c.jar

versions might be changed

import java.util.*;
import java.io.*;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;

public class JabberSmackAPI implements MessageListener {

private XMPPConnection connection;
private final String mHost = "yourserver.com"; // server IP address or the
                                                // host

public void login(String userName, String password) throws XMPPException {
    String service = StringUtils.parseServer(userName);
    String user_name = StringUtils.parseName(userName);

    ConnectionConfiguration config = new ConnectionConfiguration(mHost,
            5222, service);

    config.setSendPresence(true);
    config.setDebuggerEnabled(false);

    connection = new XMPPConnection(config);
    connection.connect();
    connection.login(user_name, password);
}

public void sendMessage(String message, String to) throws XMPPException {
    Chat chat = connection.getChatManager().createChat(to, this);
    chat.sendMessage(message);
}

public void displayBuddyList() {
    Roster roster = connection.getRoster();
    Collection<RosterEntry> entries = roster.getEntries();

    System.out.println("\n\n" + entries.size() + " buddy(ies):");
    for (RosterEntry r : entries) {
        System.out.println(r.getUser());
    }
}

public void disconnect() {
    connection.disconnect();
}

public void processMessage(Chat chat, Message message) {
    System.out.println("Received something: " + message.getBody());
    if (message.getType() == Message.Type.chat)
        System.out.println(chat.getParticipant() + " says: "
                + message.getBody());
}

public static void main(String args[]) throws XMPPException, IOException {
    // declare variables
    JabberSmackAPI c = new JabberSmackAPI();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String msg;

    // turn on the enhanced debugger
    XMPPConnection.DEBUG_ENABLED = true;

    // Enter your login information here
    System.out.println("-----");
    System.out.println("Login information:");

    System.out.print("username: ");
    String login_username = br.readLine();

    System.out.print("password: ");
    String login_pass = br.readLine();

    c.login(login_username, login_pass);

    c.displayBuddyList();

    System.out.println("-----");

    System.out
            .println("Who do you want to talk to? - Type contacts full email address:");
    String talkTo = br.readLine();

    System.out.println("-----");
    System.out.println("All messages will be sent to " + talkTo);
    System.out.println("Enter your message in the console:");
    System.out.println("-----\n");

    while (!(msg = br.readLine()).equals("bye")) {
        c.sendMessage(msg, talkTo);
    }

    c.disconnect();
    System.exit(0);
}

}

Solution 2

I tried the example with only smack and smackx added in my dependency of pom and it is working fine.

<dependency>
    <groupId>org.igniterealtime.smack</groupId>
    <artifactId>smack</artifactId>
    <version>3.3.1</version>
</dependency>
<dependency>
    <groupId>org.igniterealtime.smack</groupId>
    <artifactId>smackx</artifactId>
    <version>3.3.1</version>
</dependency>

For this you will need to add one repository too

<repository>
    <id>nexus.opencastProject.org</id>
    <url>http://repository.opencastproject.org/nexus/content/repositories/public</url>
    <name>Opencast Nexus All Public Project Repository</name>
</repository>

Hope this helps.

Solution 3

For Smack 4.1, the MessageListener interface became ChatMessageListener. MessageListener still exists, but it has a different interface contract (processMessage takes only a Message, not a Chat).

Share:
15,687
Flame_Phoenix
Author by

Flame_Phoenix

I have been programming all my life since I was a little boy. It all started with Warcraft 3 and the JASS and vJASS languages that oriented me into the path of the programmer. After having that experience I decided that was what I wanted to do for a living, so I entered University (FCT UNL ftw!) where my skills grew immensely and today, after several years of studying, professional experience and a master's degree, I have meddled with pretty much every language you can think of: from NASM to Java, passing by C# Ruby, Python, and so many others I don't even have enough space to mention them all! But don't let that make you think I am a pro. If there is one thing I learned, is that there is always the new guy can teach me. What will you teach me?

Updated on June 19, 2022

Comments

  • Flame_Phoenix
    Flame_Phoenix about 2 years

    I am still trying to learn how to properly work with the java Smack API, so I followed a mini-tutorial in a java programming forum here:

    I then changed the code to my needs. The code is posted below:

    import java.util.*;
    import java.io.*;
    
    import org.jivesoftware.smack.Chat;
    import org.jivesoftware.smack.ConnectionConfiguration;
    import org.jivesoftware.smack.MessageListener;
    import org.jivesoftware.smack.Roster;
    import org.jivesoftware.smack.RosterEntry;
    import org.jivesoftware.smack.XMPPConnection;
    import org.jivesoftware.smack.XMPPException;
    import org.jivesoftware.smack.packet.Message;
    
    public class JabberSmackAPI implements MessageListener{
    
        private XMPPConnection connection;
    
        public void login(String userName, String password) throws XMPPException
        {
            ConnectionConfiguration config = new ConnectionConfiguration("localhost", 5222);
            connection = new XMPPConnection(config);
    
            connection.connect();
            connection.login(userName, password);
        }
    
        public void sendMessage(String message, String to) throws XMPPException
        {
            Chat chat = connection.getChatManager().createChat(to, this);
            chat.sendMessage(message);
        }
    
        public void displayBuddyList()
        {
            Roster roster = connection.getRoster();
            Collection<RosterEntry> entries = roster.getEntries();
    
            System.out.println("\n\n" + entries.size() + " buddy(ies):");
            for(RosterEntry r:entries)
            {
                System.out.println(r.getUser());
            }
        }
    
        public void disconnect()
        {
            connection.disconnect();
        }
    
        public void processMessage(Chat chat, Message message)
        {
            System.out.println("Received something: " + message.getBody());
            if(message.getType() == Message.Type.chat)
                System.out.println(chat.getParticipant() + " says: " + message.getBody());
        }
    
        public static void main(String args[]) throws XMPPException, IOException
        {
            // declare variables
            JabberSmackAPI c = new JabberSmackAPI();
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String msg;
    
    
            // turn on the enhanced debugger
            XMPPConnection.DEBUG_ENABLED = true;
    
    
            // Enter your login information here
            System.out.println("-----");
            System.out.println("Login information:");
    
            System.out.print("username: ");
            String login_username = br.readLine();
    
            System.out.print("password: ");
            String login_pass = br.readLine();
    
            c.login(login_username, login_pass);
    
            c.displayBuddyList();
    
            System.out.println("-----");
    
            System.out.println("Who do you want to talk to? - Type contacts full email address:");
            String talkTo = br.readLine();
    
            System.out.println("-----");
            System.out.println("All messages will be sent to " + talkTo);
            System.out.println("Enter your message in the console:");
            System.out.println("-----\n");
    
            while( !(msg=br.readLine()).equals("bye"))
            {
                c.sendMessage(msg, talkTo);
            }
    
            c.disconnect();
            System.exit(0);
        }
    
    }
    

    In order to run this code, I have the following setup:

    1. An Openfire server running, with two users: admin and user1.
    2. I enabled all the ports Openfire should require to work as well
    3. Eclipse IDE, when the code sample.

    To run this sample, I run it using Eclipse IDE. I run this application 2 times. First I login with the admin user, and I say I want to contact with [email protected]. Then I run the sample again, as user1, and I say I want to contact with [email protected].

    I have the two samples running at the same time. I can write messages, but the console in the other end never seems to be receiving anything. What am I doing wrong?

    I have also checked other similar posts:

    However, they are also for specific cases and do not seem to help me, as I would like to have this sample running properly. What am I doing wrong?

  • Flame_Phoenix
    Flame_Phoenix over 10 years
    I have the following jars: smack.jar, smackx.jar, smackx-debug.jar, smackx-jingle.jar. Are they not supposed to contain the ones you mention?
  • Chathura Wijesinghe
    Chathura Wijesinghe over 10 years
    might be those inside the smack.jar, did you get any errors ?
  • Xairoo
    Xairoo over 10 years
    You don't need to include any extra jars. The first two mentioned aren't needed, as the connection is not http based, and the other two are rolled into the smack jars already.