2016-05-13 89 views
0

我有功能的onMessage氛圍:服務器接收其消息

@ManagedService(path = "/atmosphere/formuserpresence/{id}") 
public class FormUserPresenceUpdate extends AtmosphereHelper 
{ 

    @Message 
    public final void onMessage(final String message) throws IOException 
    { 
     ... 
     ... 
     ... 
     ... 
     broadcast(FormUserPresenceUpdate.class, "/atmosphere/formuserpresence/" + statusMessage.getId(), returnArrayString); 
    } 

} 

一個ManagedService我有客戶端 - 服務器的通信。幾個客戶可以使用他們的ID來訂閱這個頻道。然後,客戶端可以發送狀態,像

消息= { IDENT: 「uniqId」, 狀態: 「statusMessageValue」 });

類FormUserPresenceUpdate存儲所有客戶端的所有接收狀態,並通過廣播函數將其作爲數組作爲消息(returnArrayString)返回。

問題是,無論客戶端是否收到正確的值(消息數組),服務器也會從本身接收此數組並且無法解析它。所以問題是:這種情況的解決方案是什麼?我可以以某種方式使它成爲這樣,而不是通過服務器本身發送這組消息?或者我應該創建第二個頻道(我真的不想那麼做)?

回答

1

你應該定義你的消息作爲一類,並定義爲這個類的一個解碼器;)

public class Message { 
    private String ident; 
    private String status; 
    ... 

    getter and setter method. 

    ... 
} 

解碼器(這將取決於com.fasterxml.jackson.databind.ObjectMapper):

public class MessageDecoder implements Decoder<String, Message> { 

    private ObjectMapper mapper = new ObjectMapper(); 

    @Override 
    public Message decode(String s) { 
     try { 
      return mapper.readValue(s, Message.class); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

並添加decoders = {MessageDecoder.class}@Message

@Message(decoders = {MessageDecoder.class}) 
public final void onMessage(final String message) throws IOException 
{ 
    ... 
    ... 
    ... 
    ... 
    broadcast(FormUserPresenceUpdate.class, "/atmosphere/formuserpresence/" + statusMessage.getId(), returnArrayString); 
} 

還有其他r解決方案,使用JSONParser來確定消息是否可以被解析爲消息類,如果不是,則返回@Messsage方法。

+0

感謝您的工作答案。我用'return message'解決了我的特殊問題,取代了廣播功能。通過這種方式,所有用戶都收到這條消息,但服務器沒有,這對我來說很好。 在這裏還發現了一個提示[鏈接](http://atmosphere-framework.2306103.n4.nabble.com/ManagedService-with-Post-tp4657184p4657185.html)在哪裏說,如果解碼器的onMessage '方法無法解碼對象,這個'onMessage'將被跳過。我認爲,這是值得添加到您的文章爲其他用戶。 無論如何,標記爲接受的問題,謝謝。 :-) – CodeMonkey