1

如何使用嵌入式 tomcat 在不使用, , ,注释的情况下为特定类添加ServerEndpointOnOpen,OnMessage和事件处理程序?OnClose@ServerEndpoint("/myUrl")@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给了你java.lang.NullPointerException,我不确定这是否是正确的做法。

4

1 回答 1

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);
        }
      }
  });
}
于 2015-04-29T17:11:12.297 回答