将ServerEndpoint添加到没有注释的Tomcat实例

时间:2015-04-29 13:54:47

标签: java tomcat websocket embedded-tomcat-7 embedded-tomcat-8

如何在不使用ServerEndpoint的情况下为特定类添加OnOpenOnMessageOnClose@ServerEndpoint("/myUrl")事件处理程序,{{1使用嵌入式tomcat在各个类中注释,@OnOpen@OnMessage注释?

我认为这有点像:

@OnClose

但是Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); Context context = tomcat.addWebapp("/", new File(webappDir).getAbsolutePath()); context.setSessionTimeout(10080); ServerContainer serverContainer = (ServerContainer) context.getServletContext().getAttribute(ServerContainer.class.getName()); ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(MyClass.class, "myUrl").build(); serverContainer.addEndpoint(serverEndpointConfig); 给了你serverContainer,我不确定这是否是正确的做法。

1 个答案:

答案 0 :(得分:1)

另一种方法是扩展javax.websocket.Endpoint

https://blogs.oracle.com/arungupta/entry/websocket_client_and_server_endpoint

public class MyEndpoint extends Endpoint {

  @Override
  public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

      @Override
      public void onMessage(String text) {
        try {
          session.getBasicRemote().sendText(text);
        } catch (IOException ex) {
          Logger.getLogger(MyEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
  });
}