0
看来,javascript客户端无法订阅广播频道或收到广播频道。以下是在收到来自外部事件的消息后,在通知通道上广播消息的spring-cometd服务代码。 java-cometd客户端可以成功接收广播消息。即使javascript客户端也可以在服务频道上发布和订阅消息,但不能在广播频道上发布消息。订阅是在握手后完成的。Cometd javascript客户端不订阅广播频道
JavaScript代码:
var cometd = $.cometd;
cometd.addListener('/meta/handshake', _metaHandshake);// handshake listener
cometd.addListener('/meta/connect', _metaConnect);//connection connect listener
cometd.addListener('/meta/disconnect', _metaDisconnect);
cometd.handshake();
function _metaHandshake(handshake)
{
if (handshake.successful === true)
{
cometd.batch(function()
{
cometd.subscribe('/notification', function(m) {alert("hi"); });
});
}
可能出问题什么时候JavaScript客户端订阅广播频道。
@javax.inject.Named // Tells Spring that this is a bean
@javax.inject.Singleton // Tells Spring that this is a singleton
@Service("notificationService")
public class NotificationService {
private static final String channelName="/notification";
private static ServerChannel serverChannel;
private Logger logger = Logger.getLogger(this.getClass());
@Inject
private BayeuxServer bayeuxServer;
@Session
private LocalSession session;
@PostConstruct
public void init()
{
logger.debug("Notification Service Initialized");
channelSetUp();
session = bayeuxServer.newLocalSession("external");
session.handshake();
}
public void channelSetUp()
{
MarkedReference<ServerChannel> channelCreated = bayeuxServer.createChannelIfAbsent(channelName, new ServerChannel.Initializer()
{
public void configureChannel(ConfigurableServerChannel channel)
{
channel.setPersistent(true);// channel persistent
channel.addAuthorizer(GrantAuthorizer.GRANT_SUBSCRIBE_PUBLISH);
}
});
if(channelCreated.isMarked())
{
serverChannel = bayeuxServer.getChannel(channelName);
}
}
public void onExternalEvent(Map<String, Object> data)
{
// ServerChannel serverChannel = this.bayeuxServer.getChannel(channelName);
// logger.debug("Notify MessageData from JMS ::" + data.toString());
if (serverChannel != null)
{
// Broadcast the data
serverChannel.publish(session, data, null);
}
}
@Listener(Channel.META_SUBSCRIBE)
public void processSubscription(ServerSession remote, ServerMessage message)
{
// What channel the client wants to subscribe to ?
String channel = (String)message.get(Message.SUBSCRIPTION_FIELD);
logger.debug("Client Channel ::"+channel);
}
}
经过分析,真正的问题是只有当客户端订阅cometd服务器启动之前,cometd javascript客户端才能收到广播消息。当服务器上的java程序启动广播并在稍后订阅cometd javascript时。客户端无法接收广播消息。 – user2263197