CometD将数据发布到频道的问题

时间:2014-01-02 11:59:37

标签: push-notification cometd ajax-polling bayeux

我是新来的,我计划向服务器发送消息并使用cometd在我的浏览器中获取消息 如果我发送消息,它会成功发送到服务器,但无法在浏览器中获取

 private void testService() {
String channelName = "/service/out";


log.info("Channel Name = " + channelName);
        log.info("bayeuxServer : " + (bayeuxServer == null ? "Is Null" : "Is Not Null"));



System.out.println("CHANNELS : " + bayeuxServer.getChannels().toString());
        System.out.println("Subscribers on /service/in = "+bayeuxServer.getChannel("/service/in").getSubscribers().toString());
        System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());

// convert to cometd format
        Map<String, Object> data = new HashMap<String, Object>(4);
        data.put("serverMsg", getDetails());
ServerChannel channel = bayeuxServer.getChannel(channelName);
subscribers = channel.getSubscribers().size();
        log.info("Subscribers = " + subscribers);
        log.info("channel = " + channel);
channel.publish(sender, data, null);


System.out.println("Session subscriptions :" + sender.getServerSession().getSubscriptions());
        System.out.println("Listeners on /service/out = "+bayeuxServer.getChannel("/service/out").getListeners().toString());
        System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());

}

但是这个没有用

  @Subscription("/service/out")
    public void echo(Message message)
    {
        System.out.println("Echo service published " + message);
    }

日志:

1

7:48:18,775 INFO  ClientHelloService [] Bayeux server =org.cometd.server.BayeuxServerImpl@1436088
17:48:18,775 INFO  ClientHelloService [] Message = Hello world
17:48:18,775 INFO  ClientHelloService [] remote Client Id = 3renjdwk25ercglzli36tudpl
17:48:18,776 INFO  ClientHelloService [] Local session = L:_21w17u5f3mvvluvp71c27yaqvt
17:48:18,776 INFO  ClientHelloService [] session = 3renjdwk25ercglzli36tudpl - last connect 1 ms ago
17:48:18,776 INFO  ClientHelloService [] Channel Name = /service/out
17:48:18,776 INFO  ClientHelloService [] bayeuxServer : Is Not Null
CHANNELS : [/service/out, /meta/subscribe, /service, /service/*, /meta, /meta/handshake, /meta/disconnect, /service/in, /meta/connect, /meta/unsubscribe]
Subscribers on /service/in = []
Subscribers on /service/out = []
17:48:18,777 INFO  ClientHelloService [] msg = Hello world
17:48:18,777 INFO  ClientHelloService [] Subscribers = 0
17:48:18,777 INFO  ClientHelloService [] channel = /service/out
17:48:18,777 DEBUG 21192840 [] <  {data={serverMsg=Hello world}, channel=/service/out}
17:48:18,777 INFO  ClientHelloService [] publish the channel
Session subscriptions :[]
Listeners on /service/out = []
Subscribers on /service/out = []

的application.js

var sendChannel = '/service/in';            // Message from jsp
var receiveChannel = '/service/*';       // Message from server
/*var cometdServerURL = 'http://127.0.0.1:8080/cometd';*/

require(['dojox/cometd', 'dojo/dom', 'dojo/domReady!'], function(cometd, dom)
{       //  // configuration object
  //  cometd.websocketEnabled = true;
   // Open connection to CometD server
    cometd.configure({
        url: location.protocol + '//' + location.host + config.contextPath + '/cometd',
        logLevel: 'debug'
    });

cometd.addListener('/meta/*', function(message)
    {
        if (message.successful)
        {
            dom.byId('status').innerHTML += '<div>CometD handshake successful</div>';

            cometd.subscribe(receiveChannel, function(message) {
                dom.byId('results').innerHTML +=' Message  from server  ' + message.data;
                dom.byId('results').innerHTML +=' Subscription to ' + receiveChannel;
            });
        }
        else if(_connectionBroken()){
            dom.byId('status').innerHTML += '<div>CometD Connection Broken</div>';
        }
        else
        {
            dom.byId('status').innerHTML += '<div>CometD handshake failed</div>';
        }
    });
dom.byId('greeter').onclick = function()
    {
        var text = dom.byId('msg').value;
        cometd.publish(sendChannel, 'Hello world');
        dom.byId('msg').value = "" ;
        dom.byId('results').innerHTML +='Message send to server' ;
    };
    cometd.handshake();
});

2 个答案:

答案 0 :(得分:0)

您的代码中存在多个错误,如下所述。

首先,您不希望在javascript中向/meta/*添加侦听器来处理if (message.successful)分支中的订阅。该分支将针对任何元消息响应执行,例如,对于订阅的响应(通过/meta/subscribe发送),在不是意图的情况下多次执行代码。

更改侦听器以侦听/meta/handshake频道并在该侦听器中执行订阅。

同样,您希望在if (_connectionBroken())侦听器中执行/meta/connect分支。

请参阅primer以构建应用程序的正确骨架。 另外,请按照tutorials更好地了解听众的角色。

其次,建议您不要从客户端订阅服务频道。 请阅读CometD concepts以了解服务频道和广播频道之间的区别,以及添加听众和订阅之间的difference

第三,当您拥有服务频道时,publish()是本地活动,因此不会向远程客户端发送任何消息。如果您真的想使用服务渠道,那么在这种情况下使用的API是ServerSession.deliver(...)

最后,您的用例由tutorials涵盖,因此我建议您按照这些使用情况进行操作。

希望有所帮助。

答案 1 :(得分:0)

var sendChannel = '/service/in';            // Message from jsp
var receiveChannel = '/service/out';       // Message from server
/*var cometdServerURL = 'http://127.0.0.1:8080/cometd';*/

require(['dojox/cometd', 'dojo/dom', 'dojo/domReady!','dojo/_base/unload'], function(cometd, dom)
{       //  // configuration object

   // Open connection to CometD server
    cometd.configure({
        url: location.protocol + '//' + location.host + config.contextPath + '/cometd',
        logLevel: 'debug'
    });
   cometd.addListener('/meta/connect', function(message) {
        var wasConnected;
        if(cometd.isDisconnected()) {
            dom.byId('status').innerHTML +=' Disconnected from the server  = ' +  message;
        }  else{
           /* dom.byId('status').innerHTML +=' Disconnected from the server  = ' +  message.data;*/
        }
    });

 // listener for handshake
    cometd.addListener('/meta/handshake', function(message)
    {
        if (message.successful)
        {
            dom.byId('status').innerHTML += '<div>CometD handshake successful</div>';
            cometd.batch(function()
            {
            cometd.subscribe(receiveChannel, function(message) {
                dom.byId('results').innerHTML +=' Message  from server  ' + message.data;
                dom.byId('results').innerHTML +=' Subscription to ' + receiveChannel;
            });
               // cometd.publish('/service/in', { name: 'World' });
            });
        }
        else if(_connectionBroken()){
            dom.byId('status').innerHTML += '<div>CometD Connection Broken</div>';
        }
        else
        {
            dom.byId('status').innerHTML += '<div>CometD handshake failed</div>';
        }
    });

    dom.byId('greeter').onclick = function()
    {
        var text = dom.byId('msg').value;
        cometd.publish(sendChannel, 'Hello world');
        dom.byId('msg').value = "" ;
        dom.byId('results').innerHTML +='Message send to server' ;
    };
    cometd.handshake();

  });

现在也无法发布到频道

@Service
public class ClientHelloService {

    static Logger log = Logger.getLogger(
            ClientHelloService.class.getName());
    String details;
    @Inject
    private BayeuxServer bayeuxServer;
    @Session
    private LocalSession sender;
    @Session
    private ClientSession bayeuxClient;
    @Session
    ServerSession session;
    int subscribers;
       // represent callback
    @Listener("/service/in")
    public void processClientHello(ServerSession session, ServerMessage message)
    {
        log.info("Bayeux server =" + bayeuxServer);
        log.info("Message = " + message.getData());
        log.info("remote Client Id = " + session.getId());
        log.info("Local session = " + sender);
        log.info("session = " + getSession());
       // log.info("sender = " + sender);
        details = (String) message.getData();
       // session.deliver(sender,"/service/out",getDetails() , null);
        testService();
    }

    private void testService() {
        // Create the channel name  using the symbol

        String channelName = "/service/out";
        log.info("Channel Name = " + channelName);
        log.info("bayeuxServer : " + (bayeuxServer == null ? "Is Null" : "Is Not Null"));
        // Initialize the channel, making it persistant
        // new sendChannel
        bayeuxServer.createIfAbsent(channelName, new ConfigurableServerChannel.Initializer() {
            public void configureChannel(ConfigurableServerChannel channel) {
                log.info("Configurable channel " + channel);
                //  channel exists even if it has no subscribers
                channel.setPersistent(true);
                channel.setLazy(true);
            }
        });
        System.out.println("CHANNELS : " + bayeuxServer.getChannels().toString());
        System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());

        // convert to cometd format
        Map<String, Object> data = new HashMap<String, Object>(4);
        data.put("serverMsg", getDetails());
        log.info("msg = " + data.get("serverMsg"));

        // Publish the channel  to all
        ServerChannel channel = bayeuxServer.getChannel(channelName);
        subscribers = channel.getSubscribers().size();
        log.info("Subscribers = " + subscribers);
        log.info("channel = " + channel);
        // publish the message
        try {
            channel.publish(getSession(), data, null);
            log.info("publish the channel");
        }
        catch (Exception e){
            System.out.println(" Exception = " + e);
        }
        System.out.println("Session subscriptions :" + sender.getServerSession().getSubscriptions());
        System.out.println("Listeners on /service/out = "+bayeuxServer.getChannel("/service/out").getListeners().toString());
        System.out.println("Subscribers on /service/out = "+bayeuxServer.getChannel("/service/out").getSubscribers().toString());

        publishData(data);
    }

    public ServerSession getSession() {
        return session;
    }

    public void setSession(ServerSession session) {
        this.session = session;
    }

    private void publishData(Map<String, Object> data) {
        System.out.println("Published data = " + data);
    }
    /* @org.cometd.annotation.Subscription("/service/out")*/
   @Subscription("/service/out")
    public void echo(Message message)
    {
        System.out.println("Echo service published " + message);
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }
}