如何以编程方式在tomcat中获取活动的websocket会话?

时间:2015-10-19 23:45:57

标签: session tomcat websocket

我正在运行tomcat 8来终止websocket连接。我想让所有活动的websocket会话对端点说。我知道,如果你有一个会话对象,你可以调用getOpenSessions()来获取所有会话,但重点是我无法访问会话对象,我需要从代码中获取所有会话。

1 个答案:

答案 0 :(得分:3)

哇,近一年后没有答案!我在使用getOpenSessions()搜索我在Tomcat 8上遇到的问题的一些线索时偶然发现了这一点。对于我的问题,我最终做了以下,这也将解决这个问题。一般来说,只需要一个静态地图,你可以在open中填充并从close中删除:

@ServerEndpoint(value="/msg/{owner}", encoders=MessageEncoder.class, decoders=MessageEncoder.class)
public class WebSocketListener {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketListener.class);
    private static Map<String, Session> sessions = new HashMap<String, Session>();

    public WebSocketListener() {
        System.out.println("created");
    }

    @OnOpen
    public void open(Session session, @PathParam("owner") String owner) {
        System.out.println("open "+owner);
        sessions.put(session.getId(), session);
        session.getUserProperties().put("owner", owner);
        System.out.println("open");
        if (session.getUserPrincipal() != null) {
            session.getUserProperties().put("owner", owner);
        }
        else {
            try {
                session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Not authorized"));
            } catch (IOException e) {
            }
        }
    }

    @OnClose
    public void close(Session session) {
        System.out.println("close");
        sessions.remove(session.getId());
    }

    @OnError
    public void onError(Throwable error) {
        logger.error("",error);
    }

    @OnMessage
    public void onMessage(final Session session, final Message message) {
        System.out.println("onMessage");
        String owner = (String)session.getUserProperties().get("owner");
        Long appId = message.getAppId();
        for (Session s:sessions.values()) {
            System.out.println(s);
            if (s.isOpen() && (message.isEcho() || s != session) && owner.equals(s.getUserProperties().get("owner")) && (appId == null || appId.equals(s.getUserProperties().get("appId")))) {
                s.getAsyncRemote().sendObject(message);
            }
        }
    }

}