我正在运行tomcat 8来终止websocket连接。我想获得所有活动的websocket会话说端点。我知道,如果你有一个会话对象,你可以调用getOpenSessions()来获得所有会话,但重点是,我没有访问会话对象,从那里我需要获得所有会话的代码。
哇,快一年了,还是没有答案!我在寻找Tomcat 8上使用getOpenSessions()的问题的一些线索时偶然发现了这个问题。对于我的问题,我最后做了下面的事情,这也会解决这个问题。一般来说,只需要一个静态映射,在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);
}
}
}
}