Websockets: restore session on page reloading

2019-09-19 07:49发布

问题:

I want: Not log out user on F5. I store user's session id in cookies and I want to renew session on F5.

I use: Peerclass on the server side to arrange communication. One browser's tab - one peer. To renew session client side just store sessionId after he's been logged in. Afterwards if client want to renew session at aonther tab, he just ask server if there is a peer with id = sessionId in CORE.peers collection. If yes - session restored.

public class Peer implements WebSocketListener {
  private org.eclipse.jetty.websocket.api.Session session;
  private int id;

  public void onWebSocketText(String s) {
    //handle request and send response via sesion
  }

  public void onWebSocketClose(int i, String s) {
    CORE.peers.add(this);
  }

  public void onWebSocketConnect(org.eclipse.jetty.websocket.api.Session session) {
    CORE.peers.remove(this);
  }

  public void onWebSocketError(Throwable throwable) {
    //...
  }
}

Problem: Each time user press F5 - websocket sends EOF message and onWebSocketClose method is called. As result - peer with user's sessionId will be removed from CORE.peers; and user won't be able to renew his session (means user will be logged out).

On the other hand I can't cease removing peers on the server side at all.

Question: How should I decide on the server side WHEN to remove peers?

回答1:

Question: How should I decide on the server side WHEN to remove peers?

In browser applications clients can vanish without explicit logout.

This is usually handled so that in addition to explicit logout, a client is also considered logged out if it hasn't made a call to the server in the last x minutes (x often being 10 or 15 minutes).

If you want clients to stay logged on for longer than that you can have the client make "keep alive" calls every (x-1) minutes for as long as the browser stays on the current website.