我正在运行tomcat 8来终止websocket连接。我想让所有活动的websocket会话对端点说。我知道,如果你有一个会话对象,你可以调用getOpenSessions()来获取所有会话,但重点是我无法访问会话对象,我需要从代码中获取所有会话。
答案 0 :(得分:3)
@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);
}
}
}
}