cometd bayeux无法向特定客户端发送消息

时间:2013-10-05 03:29:05

标签: cometd

//StockPriceEmitter is a "dead loop" thread which generate data, and invoke StockPriceService.onUpdates() to send data.
@Service
public class StockPriceService implements StockPriceEmitter.Listener
{
    @Inject
    private BayeuxServer bayeuxServer;
    @Session
    private LocalSession sender;

    public void onUpdates(List<StockPriceEmitter.Update> updates)
    {
        for (StockPriceEmitter.Update update : updates)
        {
            // Create the channel name using the stock symbol
            String channelName = "/stock/" + update.getSymbol().toLowerCase(Locale.ENGLISH);

            // Initialize the channel, making it persistent and lazy
            bayeuxServer.createIfAbsent(channelName, new ConfigurableServerChannel.Initializer()
            {
                public void configureChannel(ConfigurableServerChannel channel)
                {
                    channel.setPersistent(true);
                    channel.setLazy(true);
                }
            });

            // Convert the Update business object to a CometD-friendly format
            Map<String, Object> data = new HashMap<String, Object>(4);
            data.put("symbol", update.getSymbol());
            data.put("oldValue", update.getOldValue());
            data.put("newValue", update.getNewValue());

            // Publish to all subscribers
            ServerChannel channel = bayeuxServer.getChannel(channelName);
            channel.publish(sender, data, null); // this code works fine
            //this.sender.getServerSession().deliver(sender, channel.getId(), data, null); // this code does not work
        }
    }
}

这一行channel.publish(sender, data, null); // this code works fine工作正常,现在我不希望频道向所有客户端发布消息,我想发送给特定的客户端,所以我写这个this.sender.getServerSession().deliver(sender, channel.getId(), data, null);,但是它不起作用,浏览器无法获取消息。

提前thx。

1 个答案:

答案 0 :(得分:0)

我强烈建议您花一些时间阅读CometD concepts页面,尤其是section about sessions

您的代码无效,因为您要将邮件发送给发件人,而不是收件人

您需要选择要将消息发送到可能连接到服务器的许多远程ServerSession,并在该远程ServerSession上调用serverSession.deliver(...)

如何选择远程ServerSession取决于您的应用程序。

例如:

for (ServerSession session : bayeuxServer.getSessions())
{
    if (isAdminUser(session))
        session.deliver(sender, channel.getId(), data, null);
}

当然,您必须提供isAdmin(ServerSession)的实现和逻辑。

请注意,您无需迭代会话:如果您碰巧知道要传递的会话ID,则可以执行以下操作:

bayeuxServer.getSession(sessionId).deliver(sender, channel.getId(), data, null);

另请参阅CometD发行版附带的CometD chat demo,其中包含有关如何向特定会话发送消息的完整示例。