2011-01-22 108 views
0

我正在使用Smack 3.1.0和Java创建一个即时消息客户端。我正在运行的问题与将消息发送给特定域上的用户有关。在初始广播消息后发送消息到特定的Smack域

例如,我有两个用户,1 @ gmail.com和2 @ gmail.com。 [email protected]通过我的IM客户端登录到XMPP。 [email protected]通过gmail.com登录GChat并通过pidgin第二次登录。所以现在我有一个[email protected]实例和2个[email protected]实例。

gmail的工作方式,如果[email protected]发送消息给[email protected],gmail和pidgin客户端都会得到初始消息。但是,如果gmail实例对消息作出响应,则从此之后的每条消息仅在[email protected][email protected]的gmail实例之间进行。

我想用我的IM客户端来模仿这种行为。我认为这样做的方法是建立一个聊天,将最初的IM发送给收件人的所有实例。然后我设置一个MessageListener来侦听响应。当我收到回复时,我必须创建一个新聊天,指定[email protected]/resource。但是,我不得不写两次MessageListener。有任何想法吗?下面是我使用(AddText()只会附加消息,我的对话窗格中的方法)的一些示例代码:

recipient = buddy; 
setTitle("Instant Message - "+recipient); 
chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() { 
    public void processMessage(Chat chat, Message msg) { 
     //if(chat.getParticipant().indexOf('/')!=-1) 
     addText(msg.getBody(), chat.getParticipant(), true); 
    } 
}); 

UPDATE 我想补充下面用实际代码的答案,我用来做这个工作:

chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() { 
    public void processMessage(Chat new_chat, Message msg) { 
     if(msg.getFrom().replaceFirst("/.*", "").equals(recipient.getUser())) 
     { 
      if(buddy_resource==null || !msg.getFrom().replaceFirst(".*?/", "").equals(buddy_resource.getResource())) 
      { 
       buddy_resource = recipient.getResource(msg.getFrom().replaceFirst(".*?/", "")); 
       chat = null; 
       chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser()+"/"+buddy_resource.getResource(), new MessageListener(){ 
        public void processMessage(Chat new_chat2, Message msg) { 
         addText(msg.getBody(), new_chat2.getParticipant(), true); 
        } 
       }); 
      } 
      addText(msg.getBody(), chat.getParticipant(), true); 
     } 
    } 
}); 

总之,我发送第一条消息到收件人地址的所有资源并等待响应。当我得到响应时,我用当前的Chat对象替换一个新对象,该对象指定了响应初始消息的单个资源。代码与两个不同的MessageListener对象有点混乱,这些对象可能可以组合成一个新类。但它的工作。

回答

0

在您的MessageListener中,为什么不总是对发件人作出回应?我认为你通过调用像msg.getSender()或getFrom()(我现在在手机上,无法检查)得到它。

+0

msg.getFrom()是一个字符串。要响应发件人需要聊天newChat = connection.getChatManager()。createChat(msg.getFrom(),new MessageListener(){}); – SpaDusA 2011-01-22 03:58:46

0

到目前为止,我了解Message Carbon(XEP - 0280)将解决您的问题。 如果您启用Carbon,它会将消息分发给用户的所有记录资源。在你的情况下,如果[email protected]发送消息到[email protected],它将被分发到所有记录的[email protected]资源。 下面是使用嫌代码示例,

CarbonManager cm = CarbonManager.getInstanceFor(connection); 
cm.enableCarbons(); 
cm.sendCarbonsEnabled(); 

首先确保你的服务器支持的消息碳。 然后照常发送消息。