使用CometD Java客户端发布消息,可以被Javascript订阅者使用

问题描述:

我有一个使用CometD的Java web应用程序。工作流程很简单:使用CometD Java客户端发布消息,可以被Javascript订阅者使用

  1. 我已经定义了一个在通道“/ service/hello”上接收消息的服务。该服务需要一个参数“名称”。基于此,它创建一个名为:"/"+message.getDataAsMap().get("name")的频道。在这个频道上,它附加了一个回叫方法,它会向所有用户发回一条消息。
  2. Javascript客户端(使用dojo)向频道 发布消息“/ service/hello”并订阅名称已发送 作为参数的“/ service/hello”频道。让我们举一个例子:
.... 
    cometd.subscribe('/1234', function(message) 
    { 
        //do smth on message received; 
    }); 

    cometd.publish('/service/hello', { name: '1234' }); 
.... 

这工作得很好。现在,我想要达到的目标如下:让Javascript客户端只作为订阅者,并使用Java客户端来完成发布。 我已经尝试使用CometD2文档中给出的Java客户端API的示例,但它不能按预期工作。看起来该服务被调用,但消费者看不到这些消息。

有没有可能做到这一点?任何错误的想法?谢谢。

这里是在服务器端的代码:

公共类HelloService的延伸AbstractService { 公共HelloService中(BayeuxServer贝叶) { 超级(贝叶, “你好”); addService(“/ service/hello”,“processHello”); }

public void processHello(ServerSession remote, Message message) 
{ 
    Map<String, Object> input = message.getDataAsMap(); 
    String name = (String)input.get("name"); 
    String channelId = "/"+name; 
    addService(channelId, "processId"); 
    processId(remote, message); 

} 

public void processId(ServerSession remote, Message message) 
{ 
    Map<String, Object> input = message.getDataAsMap(); 
    String name = (String)input.get("name"); 
    int i = 0; 
    Map<String, Object> output = new HashMap<String, Object>(); 
    while(i<1){ 
     i++; 
     output.put("greeting", "Hello, " + name); 
     remote.deliver(getServerSession(), "/"+name, output, null); 
     try { 
      Thread.sleep(1000);    } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace();   } 
    } 
} } 
+0

你能发布服务器端的代码吗? – perissf

+0

我已经添加了服务器端的代码。这是来自cometd文档页面的一个适合我的案例。 – mihaela

remote.deliver()发送 “答案”,关于服务信道发布的remote会话(即,客户端)。

您应该将未经请求的消息发布到正常通道(服务器端尚不存在)。所以,你应该写点类似于

String channelName = "whatever - not beginning with /service"; 
getBayeux().createIfAbsent(channelName); 
getBayeux().getChannel(channelName).publish(getServerSession(), output, null); 
+0

谢谢。有效! – mihaela