2012-09-06 48 views
0

我想推送消息從服務器到客戶端。我正在使用DOJO 1.7,Cometd和Jetty與tomcat6集成。服務器推送使用COMETD客戶端(dojo)

//Server side code 
    public class notificationService extends AbstractService { 

public notificationService(BayeuxServer bayeux, String name) { 
    super(bayeux, name); 
    System.out.println("Inside constrcutor of Notification Service"); 
    addService("/notification", "processNotification"); 
} 


    public void processNotification(ServerSession remote,ServerMessage.Mutable message)  
     { 
    System.out.println("Inside process Notification"); 
    Map<String,Object> response = new HashMap<String,Object>(); 
    response.put("payload",new java.util.Date()); 
      getBayeux().createIfAbsent("/notification"); 
      getBayeux().getChannel("/notification").publish(getServerSession(),response,null); 
      //remote.deliver(getServerSession(),"/notification", response, null); 
     } 

     //Client Side Code (DOJO) 

     var cometd = dojox.cometd; 
     cometd.init("http://serverip:port/cometd") 
     cometd.publish('/notification',{ mydata: { foo: 'bar' } }); 
     cometd.subscribe('/notification', function(message) 
      { 
        //alert("Message received" + message.data.payload); 
        //alert(message.data.payload); 
        alert("Message received"); 
      }); 

我想廣播消息給所有的客戶訂閱特定的頻道。當m使用remore.deliver時,它將消息發送給單個客戶端,但不發送給訂閱該頻道的所有客戶端。 channel.publish不適合我...任何幫助和意見,高度讚賞。

回答

2

您的客戶正在發佈到頻道/notification,這是一個廣播頻道(請參閱http://docs.cometd.org/reference/#concepts_channels的定義),以便消息不僅可以被您的服務接收,還可以廣播給該頻道的所有訂閱者。

然後在你的服務,你叫ServerChannel.publish()將發送另一個消息到/notification通道的用戶(除了服務本身 - 有一個無限循環預防)。

執行此類操作的更好方法是使用服務通道(例如/service/notification)將來自客戶端的初始消息發送到服務。 然後,服務可以像現在一樣廣播到頻道/notification

調用ServerChannel.publish()是從服務廣播消息的正確方式。 不幸的是,你不明確爲什麼不適合你,所以我忍不住。

我會從第一條消息的客戶端和服務之間的服務通道開始。

還要注意,Tomcat 6並不是真正的CometD最好的解決方案,因爲它不支持異步servlet(Servlet 3)。

您最好使用符合Servlet 3的容器,如Jetty 8

相關問題