In my application I have a sessionhandler that stores all connected sessions when they connect and removes them if they disconnects properly. If they do not I keep the sessions and if they reconnect I replace the old session with the new one. (The code below seems stupid, but it is just to make my point)
@ServerEndpoint(value = "/games")
public class GameEndPoint {
@Inject
private GameSessionHandler sessionHandler;
@OnOpen
public void open(Session session) {
sessionHandler.addSession(session);
}
@OnClose
public void close(Session session, CloseReason closeReason) {
sessionHandler.sessionClosed(session, closeReason.getCloseCode());
}
@OnError
public void onError(Throwable error) {
LOGGER.log(Level.SEVERE, "Socket connection error", error);
}
@OnMessage
public String handleMessage(String payload, Session session) {
return payload;
}
}
@Singleton
public class GameSessionHandler implements Serializable {
private final Set<Session> sessions = new HashSet<>();
public void addSession(Session session) {
for(Session existing: sessions) {
if(existing.equals(session)) {//DOES NOT WORK
//client reconnected!
sessions.remove(existing);
break;
}
}
sessions.add(session);
}
public void removeSession(Session session) {
if (CloseReason.CloseCodes.NORMAL_CLOSURE.equals(reason)) {
sessions.remove(session)
}
}
}
The problem is: how can I check that the session is for a client that was connected earlier, so that I can replace the session with the new open one?
Edit: This is needed because my client is a html5 application where the user can refresh/navigate on the page, and then the connection is lost. Whenever he attempts to reconnect I want to know which game he was currently playing. If the user is on a unstable connection (ie. on a mobile phone), also the connection will be lost from time to time.