gpt4 book ai didi

java - 使用 CometD Java 客户端发布可由 Javascript 订阅者使用的消息

转载 作者:搜寻专家 更新时间:2023-11-01 03:12:15 25 4
gpt4 key购买 nike

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

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

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

这很好用。现在,我想要实现的是:让 Javascript 客户端仅作为订阅者和一个进行发布的 Java 客户端。我已经使用 CometD2 文档中针对 Java 客户端 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(); }
}
}
}

最佳答案

remote.deliver() 将“答案”发送到在服务 channel 上发布的远程 session (即客户端)。

您应该将未经请求的消息发布到正常 channel (服务器端尚不存在)。所以,你应该写这样的东西

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

关于java - 使用 CometD Java 客户端发布可由 Javascript 订阅者使用的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7658643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com