如何以编程方式在嵌入式tomcat中添加websocket端点?

时间:2015-10-28 14:17:33

标签: java tomcat embedded-tomcat-7

我已经尝试了几周让websockets使用嵌入式tomcat。我已经尝试在tomcat单元测试中模拟示例无济于事。这是我第一次尝试使用websockets,所以我可能犯了一个愚蠢的错误。有没有人有嵌入式tomcat websockets的简单“回声”示例?

public void run() {

    if(!new File(consoleAppBase).isDirectory())
    {
         consoleAppBase = Paths.get("").toAbsolutePath().toString() + File.separatorChar + "wepapp";
    }

    tomcat = new Tomcat();

    tomcat.getService().removeConnector(tomcat.getConnector()); // remove default
    tomcat.getService().addConnector(createSslConnector(ConfigManager.getWeb_securePort())); // add secure option

    StandardServer server = (StandardServer) tomcat.getServer();
    AprLifecycleListener listener = new AprLifecycleListener();
    server.addLifecycleListener(listener);

    try {
        SecurityConstraint constraint = new SecurityConstraint();
        constraint.setDisplayName("SSL Redirect Constraint");
        constraint.setAuthConstraint(true);
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        constraint.addAuthRole("administrator");
        constraint.addCollection(collection);

        //create the console webapp.
        consoleContext = tomcat.addWebapp(consoleContextPath, consoleAppBase);
        consoleContext.addConstraint(constraint);

        //this allows that little login popup for the console webapp.
        LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod("BASIC");
        consoleContext.setLoginConfig(loginConfig);
        consoleContext.addSecurityRole("administrator");

        //this creates a valid user.
        tomcat.addUser(ConfigManager.getWeb_username(), Encryptor.decrypt(ConfigManager.getWeb_passwordEncrypted()));
        tomcat.addRole("admin", "administrator");

    } catch (ServletException e) {
        LogMaster.getWebServerLogger().error("Error launching Web Application. Stopping Web Server.");
        LogMaster.getErrorLogger().error("Error launching Web Application. Stopping Web Server.", e);
        return;
    }

    addServlets(); // this is where I usually call a convenience method to add servlets

    // How can I add websocket endpoints instead?

}

3 个答案:

答案 0 :(得分:2)

我以这种方式使用WebSocket:

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
//...

@ServerEndpoint("/move")
public class TestWebSocketEndPoint {//@OnMessage 
public void onMessage(Session session, String message) {}
private static final Queue<Session> QUEUE = new ConcurrentLinkedQueue<Session>();

@OnOpen
public void open(Session session) {
    QUEUE.add(session);
}

@OnError
public void error(Session session, Throwable t) {
    StaticLogger.log(TestWebSocketEndPoint.class, t);
    QUEUE.remove(session);
}

@OnClose
public void closedConnection(Session session) {
    QUEUE.remove(session);
}

public static void sendToAll(String message) throws IOException {
    ArrayList<Session> closedSessions = new ArrayList<Session>();
    for (Session session : QUEUE) {
        if (!session.isOpen()) {
            closedSessions.add(session);
        } else {
            session.getBasicRemote().sendText(message);
        }
    }
    QUEUE.removeAll(closedSessions);
}
}

和JS致电:

var webSocket;
webSocket = new WebSocket("ws://localhost:8585/test/move");
webSocket.onmessage = function () {
    alert('test');
}


Java调用:

  TestWebSocketEndPoint.sendToAll(result);

答案 1 :(得分:1)

对于程序化(非注释)端点,您必须提供一个实现Endpoint的类作为服务器端,然后:

  1. 在WAR文件中部署一个实现ServerApplicationConfig的类,该类提供有关在WAR文件中找到的部分或全部非注释EndpointConfig实例的Endpoint信息,或者
  2. 在您的网络应用的部署阶段调用ServerContainer.addEndpoint()
  3. 请参阅Java™API for WebSocket,JSR 356。

答案 2 :(得分:0)

据我所知,配置websocket与配置servlet(或servlet过滤器)相同。在web.xml中,您必须包含<async-supported>true</async-supported>

我认为在java配置中有类似的标志。

相关问题