2013-10-05 63 views
-1
//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工作得很好,現在我不想渠道發佈的消息與它subscirbed所有客戶端,我想發送到特定的客戶端,因此我寫這個this.sender.getServerSession().deliver(sender, channel.getId(), data, null);,但它不起作用,瀏覽器無法獲得消息。的cometd貝葉不能將消息發送到特定的客戶端

thx提前。

回答

0

我強烈建議您花一些時間閱讀CometD concepts頁面,特別是section about sessions

,因爲您要發送消息到發件人,不給收件人您的代碼不起作用。

您需要選擇要將消息發送到可能連接到服務器的許多遠程設備,並在該遠程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 ,其中包含如何將消息發送到特定會話的完整示例。

相關問題