send and receiving message using smack API

后端 未结 3 2048
北恋
北恋 2021-01-12 00:53

I have setup my open fire(jabber server) on local machine with two user testuser1 and testuser2 .using Spark client both users perform chat without any issue,it\'s nice.

3条回答
  •  隐瞒了意图╮
    2021-01-12 01:02

    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!

提交回复
热议问题