15

我正在开发一个使用 Websockets (Java EE 7) 将消息异步发送到所有连接的客户端的应用程序。每当创建新文章(我的应用程序中的参与模式)时,服务器(Websocket 端点)应该发送这些消息。

每次与 websocket 端点建立连接时,我都会将相应的会话添加到列表中,我可以在外部访问该列表。

但是我遇到的问题是,当我访问所有客户端从外部(任何其他业务类)连接到的这个创建的 websocket 端点时,我已经获得了现有实例(如单例)。

那么,您能否建议我一种获取现有 websocket 端点实例的方法,因为我无法将其创建为 new MyWebsocketEndPoint() 因为只要来自客户端的请求,它将由 websocket 内部机制创建已收到。

对于参考:

private static WebSocketEndPoint INSTANCE = null;

public static WebSocketEndPoint getInstance() {
if(INSTANCE == null) {
// Instead of creating a new instance, I need an existing one
    INSTANCE = new WebSocketEndPoint ();
}
        return INSTANCE;
}

提前致谢。

4

2 回答 2

23

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

该类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 会执行以下操作:

...
@Inject
Event<ArticleEvent> newArticleEvent;

public void publishArticle(Article article) {
  ...
  newArticleEvent.fire(new ArticleEvent(article));
  ...
}

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

编辑:修改了@Observer使用事件作为参数的方法。

编辑2:根据@gcvt,将循环包装在broadcastArticle中。

编辑 3:更新了 Java EE 7 教程的链接。干得好,甲骨文。嘘。

于 2013-08-29T00:19:46.523 回答
9

实际上,WebSocket API 提供了一种控制端点实例化的方法。请参阅https://tyrus.java.net/apidocs/1.2.1/javax/websocket/server/ServerEndpointConfig.Configurator.html

简单示例(取自Tyrus - WebSocket RI测试):

    public static class MyServerConfigurator extends ServerEndpointConfig.Configurator {

        public static final MyEndpointAnnotated testEndpoint1 = new MyEndpointAnnotated();
        public static final MyEndpointProgrammatic testEndpoint2 = new MyEndpointProgrammatic();

        @Override
        public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
            if (endpointClass.equals(MyEndpointAnnotated.class)) {
                return (T) testEndpoint1;
            } else if (endpointClass.equals(MyEndpointProgrammatic.class)) {
                return (T) testEndpoint2;
            }

            throw new InstantiationException();
        }
    }

您需要将其注册到端点:

@ServerEndpoint(value = "/echoAnnotated", configurator = MyServerConfigurator.class)
public static class MyEndpointAnnotated {

    @OnMessage
    public String onMessage(String message) {

        assertEquals(MyServerConfigurator.testEndpoint1, this);

        return message;
    }
}

或者您也可以将它与编程端点一起使用:

public static class MyApplication implements ServerApplicationConfig {
    @Override
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) {
        return new HashSet<ServerEndpointConfig>
          (Arrays.asList(ServerEndpointConfig.Builder
            .create(MyEndpointProgrammatic.class, "/echoProgrammatic")
            .configurator(new MyServerConfigurator())
            .build()));
    }

    @Override
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
        return new HashSet<Class<?>>(Arrays.asList(MyEndpointAnnotated.class));
    }

当然,您是否将为所有端点使用一个配置器(如呈现的代码段中的丑陋 ifs),或者您是否将为每个端点创建单独的配置器,这取决于您。

请不要照原样复制提供的代码 - 这只是 Tyrus 测试的一部分,它确实违反了一些基本的 OOM 范例。

有关完整测试,请参阅https://github.com/tyrus-project/tyrus/blob/1.2.1/tests/e2e/src/test/java/org/glassfish/tyrus/test/e2e/GetEndpointInstanceTest.java

于 2013-08-29T09:39:52.710 回答