栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何获取现有的Websocket实例

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何获取现有的Websocket实例

容器会为每个客户端连接创建一个单独的终结点实例,因此您无法做您想做的事情。但是我认为您想要做的是在事件发生时向所有活动的客户端连接发送消息,这非常简单。

javax.websocket.Session
类有
getBasicRemote
检索方法
RemoteEndpoint.Basic
,表示与该会话相关的端点实例。

您可以通过调用来检索所有打开的会话

Session.getOpenSessions()
,然后遍历它们。该循环将向每个客户端连接发送一条消息。这是一个简单的例子:

@ServerEndpoint("/myendpoint")public class MyEndpoint {  @onMessage  public void onMessage(Session session, String message) {    try {        for (Session s : session.getOpenSessions()) {        if (s.isOpen()) {          s.getBasicRemote().sendText(message);        }    } catch (IOException ex) { ... }  } }

但是在您的情况下,您可能想使用CDI事件来触发对所有客户端的更新。在这种情况下,您将创建一个CDI事件,您的Websocket端点类中的方法会观察到此事件:

@ServerEndpoint("/myendpoint")public class MyEndpoint {  // EJB that fires an event when a new article appears  @EJB  ArticleBean articleBean;  // a collection containing all the sessions  private static final Set<Session> sessions =Collections.synchronizedSet(new HashSet<Session>());  @onOpen  public void onOpen(final Session session) {    // add the new session to the set    sessions.add(session);    ...  }  @onClose  public void onClose(final Session session) {    // remove the session from the set    sessions.remove(session);  }  public void broadcastArticle(@Observes @NewArticleEvent ArticleEvent articleEvent) {    synchronized(sessions) {      for (Session s : sessions) {        if (s.isOpen()) {          try { // send the article summary to all the connected clients s.getBasicRemote().sendText("New article up:" + articleEvent.getArticle().getSummary());          } catch (IOException ex) { ... }        }      }    }  }}

上面的示例中的EJB将执行以下操作:

...@InjectEvent<ArticleEvent> newArticleEvent;public void publishArticle(Article article) {  ...  newArticleEvent.fire(new ArticleEvent(article));  ...}

请参阅有关WebSocket和CDI事件的Java EE 7教程章节。

编辑:修改了

@Observer
将事件用作参数的方法。

编辑2:按照@gcvt,以同步方式将循环包装在broadcastArticle中。

编辑3:更新了指向Java EE 7教程的链接。干得好,Oracle。嘘。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495091.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号