send and receiving message using smack API

萝らか妹 提交于 2019-12-01 03:48:45

I had a similar problem, after following the tutorial here (http://www.javacodegeeks.com/2010/09/xmpp-im-with-smack-for-java.html) and this is what I found:

When you create the chat, you chat the user you want to connect to (eg in my case "user1@gbd038"). This works fine if user1 is using a GUI client such as Spark (which presumably has built-in support and/or error handling for this), and user1 will receive the message. This process attaches the messageListener to a chat now associated with "user1@gbd038". However, when I reply from Spark as user1, the chat that smack receives is actually coming through complete with the location tag, eg:

Received message 'hi' from user1@gbd038/Spark 2.6.3

So it creates a new chat that the application is not listening for (and therefore your application will not receive / print out). I have found two ways to solve this problem:

  1. use the location tag when starting the conversation (although this doesn't seem very scalable or robust):

    xmppManager.sendMessage("Hello mate", "user1@gbd038/Spark 2.6.3");

  2. as Robin suggested, use a ChatManagerListener (which will create a new chat when receiving the reply from user1, which can be forwarded to the messageListener):

    chatManager = connection.getChatManager();
    messageListener = new MyMessageListener();
    
    chatManagerListener = new ChatManagerListener() {
        @Override
        public void chatCreated(Chat chat, boolean createdLocally) {
            chat.addMessageListener(messageListener);
        }
    };
    chatManager.addChatListener(chatManagerListener);
    

Hope that helps someone in the same position!

You are creating a chat and sending a chat message from both ends but not listening for a chat from either. Use a ChatManagerListener to listen for incoming chats from other clients.

Use below code for sending and receiving message

@Override
         public void processMessage(Chat chat, Message message) {
             // Print out any messages we get back to standard out.
             System.out.println("Received message: " + message);
         }

     });

chat.sendMessage("How are you dear !!");
System.out.println(" Send Message succesfully");

For full code example visit How to send message using smack api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!