How to receive Incoming XMPP Messages using Smack?
Asked Answered
H

4

24

I read some examples and tested them but all of them need to start a chat with someone first to receive Incoming Messages... I want to retrieve this Incoming Messages without need to talk first to the jid anyone can give an example ?

Hystero answered 14/2, 2011 at 16:46 Comment(1)
what is your server ?Bodine
P
30

You need to register a ChatListener to be notified of new chats, then you can add a message listener to them like normal:

connection.getChatManager().addChatListener(new ChatManagerListenerImpl());

....

private class ChatManagerListenerImpl implements ChatManagerListener {

    /** {@inheritDoc} */
    @Override
    public void chatCreated(final Chat chat, final boolean createdLocally) {
        chat.addMessageListener(...);
    }

}
Periotic answered 14/2, 2011 at 16:56 Comment(4)
@cris Smith hi ! thx for ur reply :) could please give a full example ? i'm really in trouble :SHystero
very useful! for the info the addChatListener can be call before the login.Lamarckian
I used the same approach, but offline messages are not received in order. How can i resolve this?Cockayne
@Periotic Smith i have created a room and added 2 users and was able to send messages to the room. Now i want to receive the messages sent by the other users ... How to acheive this ... ??? Is this possible using this api ??Berliner
M
15

i just wanted to add a copy & paste sample:

  // connect to server
  XMPPConnection connection = new XMPPConnection("jabber.org");
  connection.connect();
  connection.login("user", "password"); // TODO: change user and pass

  // register listeners
  ChatManager chatmanager = connection.getChatManager();
  connection.getChatManager().addChatListener(new ChatManagerListener()
  {
    public void chatCreated(final Chat chat, final boolean createdLocally)
    {
      chat.addMessageListener(new MessageListener()
      {
        public void processMessage(Chat chat, Message message)
        {
          System.out.println("Received message: " 
            + (message != null ? message.getBody() : "NULL"));
        }
      });
    }
  });

  // idle for 20 seconds
  final long start = System.nanoTime();
  while ((System.nanoTime() - start) / 1000000 < 20000) // do for 20 seconds
  {
    Thread.sleep(500);
  }
  connection.disconnect();

This sample connects to jabber.org and displays every received message on the console.

Metabolic answered 19/2, 2011 at 20:59 Comment(1)
I am doing the same, but unable to receive the message. There is a blog post I explain what is going on with my code. rmwaqas.com/chat-client-using-smackMidshipman
A
9

Please find the following code.
Please add smack.jar & smackx.jar to your build path

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

public class GoogleTalkDemo extends Thread{
    private XMPPConnection xmppConnection;

    public void connect(String server, int port, String s) throws Exception {
        xmppConnection = new XMPPConnection(new ConnectionConfiguration(server, port,s));
        xmppConnection.connect();
    }

    public void disconnect(){
        if(xmppConnection != null){
            xmppConnection.disconnect();
            interrupt();
        }
    }

    public void login(String username, String password) throws Exception{
        connect("talk.google.com", 5222, "gmail.com");
        xmppConnection.login(username, password);
    }

    public void run(){
        try {
            login("[email protected]", "your password");
            System.out.println("Login successful");
            listeningForMessages();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String args[]) throws Exception {
        GoogleTalkDemo gtd = new GoogleTalkDemo();
        gtd.run();
    }

    public void listeningForMessages() {
        PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
        PacketCollector collector = xmppConnection.createPacketCollector(filter);
        while (true) {
            Packet packet = collector.nextResult();
            if (packet instanceof Message) {
                Message message = (Message) packet;
                if (message != null && message.getBody() != null)
                    System.out.println("Received message from "
                            + packet.getFrom() + " : "
                            + (message != null ? message.getBody() : "NULL"));
            }
        }
    }

}
Arvonio answered 10/9, 2012 at 8:53 Comment(1)
@Samik from where you find out this smack.jar & smackx.jar file i have dolwoad smack_4_1_3.zip but i cannot found this two jar fileMicrosome
F
3
private MultiUserChat   muc; /* Initialize muc */

private void listeningForMessages() 
    {
        muc.addMessageListener(new PacketListener() {
            public void processPacket(Packet packet) 
            {
                final Message message = (Message) packet;

                    // Do your action with the message              
            }
        });
    }
Feuchtwanger answered 20/6, 2013 at 9:48 Comment(4)
Hi @Feuchtwanger Your answer helped me a lot. The above method processPacket is called when i send a message to user but if the user reply to my message then this is not geting called ?? Plz help ...Berliner
It should get called. I'm not sure why it's not working for you.Feuchtwanger
Hi @Feuchtwanger if you want the listener of group message then you should addPacketListner to connectionBerliner
how do you detect whether it is incoming or outgoing as it seems to be similar message object in the latest versionsScup

© 2022 - 2024 — McMap. All rights reserved.