質問

I have a Java web application that uses CometD. The workflow is simple:

  1. I have defined a service that acts upon receiving messages on channel "/service/hello". This service expects a parameter "name". Based on this it creates a channel named: "/"+message.getDataAsMap().get("name"). To this channel it attaches a callback method that will send back a message to all subscribers.
  2. The Javascript client (uses dojo) publishes a message to the channel "/service/hello" and subscribes to the channel whose name has sent to the "/service/hello" as parameter. Lets take an example:
....
    cometd.subscribe('/1234', function(message)
    {
                    //do smth on message received;
     });

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

This works fine. Now ,what I want to achieve is the following: to have the Javascript clients only as subscribers and a Java client that does the publishing. I have tried this using the examples given in the CometD2 documentation for Java Client API, but it doesn't work as expected. It seems that the service is called but the messages aren't seen by the Javascript consumers.

Is it possible to achieve this? Any ideas of what is wrong? Thanks.

Here is the code on the server side:

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() sends the "answer" to the remote session (i.e. the client) that published on the service channel.

You should publish an unsolicited message to a normal channel (which on the server side does not exist yet). So, you should write something like

String channelName = "whatever - not beginning with /service";
getBayeux().createIfAbsent(channelName);
getBayeux().getChannel(channelName).publish(getServerSession(), output, null); 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top