首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在嵌入式tomcat中以编程方式添加websocket端点?

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

Stack Overflow用户
提问于 2015-10-28 22:17:33
回答 2查看 3.7K关注 0票数 2

几个星期以来,我一直在尝试让websockets与嵌入式tomcat一起工作。我已经尝试模拟tomcat单元测试中的示例,但都没有用。这是我第一次尝试使用websockets,所以我可能犯了一个愚蠢的错误。有没有嵌入式tomcat websockets的简单"Echo“示例?

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?

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-10-28 22:26:34

我以这样的方式使用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);
票数 0
EN

Stack Overflow用户

发布于 2015-10-28 22:26:33

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

我假设在java配置中也有类似的标志。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33393497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档