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



我是cometd的新手,我计划向服务器发送消息,并使用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();
});

您的代码中有几个错误,如下所述。

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

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

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

请参阅入门教程,构建一个合适的应用程序框架。此外,请遵循教程以更好地理解听众的角色。

其次,不建议您从客户端订阅服务频道。阅读CometD的概念,了解服务频道和广播频道之间的区别,以及添加侦听器和订阅之间的区别。

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

最后,教程涵盖了您的用例,因此我建议您遵循这些教程,您的应用程序就会正常工作。

希望能有所帮助。

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;
}
}

相关内容

  • 没有找到相关文章

最新更新