2011-01-22 70 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(); 

首先確保你的服務器支持的消息碳。 然後照常發送消息。