使用COMETD将服务器推送到客户端(dojo)

Server push using COMETD to client(dojo)

本文关键字:客户端 dojo COMETD 服务器 使用      更新时间:2023-09-26

我正在尝试将消息从服务器推送到客户端。我使用的是DOJO 1.7、Comed和Jetty与tomcat6集成。

 //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对我不起作用…非常感谢任何帮助和评论。

您的客户端正在发布到频道/notification,这是一个广播频道(请参阅http://docs.cometd.org/reference/#concepts_channels对于定义),这样消息不仅会被您的服务接收,还会广播给该频道的所有订户。

然后,在您的服务中,您调用ServerChannel.publish(),它将向/notification信道的订户发送另一条消息(除了服务本身,还有无限循环防止)。

执行此类操作的更好方法是使用服务通道,例如/service/notification,将初始消息从客户端发送到服务。然后,该服务可以像现在一样向频道/notification进行广播。

调用ServerChannel.publish()是从服务广播消息的正确方式。不幸的是,你没有具体说明为什么不适合你,所以我帮不上忙。

首先,我将在您的客户端和第一条消息的服务之间使用一个服务通道。

还要注意,Tomcat6并不是CometD的最佳解决方案,因为它不支持异步Servlet(Servlet 3)。

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