4

我有一个使用 CometD 的 Java Web 应用程序。工作流程很简单:

  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 Client API 提供的示例进行了尝试,但它没有按预期工作。似乎调用了服务,但 Javascript 消费者看不到消息。

有可能实现这一目标吗?有什么错误的想法吗?谢谢。

这是服务器端的代码:

public class HelloService extends AbstractService {
    public HelloService(BayeuxServer bayeux)
    {
        super(bayeux, "hello");
        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();            }
        }
    } 
}
4

1 回答 1

3

remote.deliver()将“答案”发送到remote在服务通道上发布的会话(即客户端)。

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

String channelName = "whatever - not beginning with /service";
getBayeux().createIfAbsent(channelName);
getBayeux().getChannel(channelName).publish(getServerSession(), output, null); 
于 2011-10-05T10:30:41.670 回答