WebSockets的延迟断开连接机制



我正在尝试为我正在开发的WebSocket聊天添加一个"延迟断开连接"机制。这意味着,如果用户断开连接,但在一定的时间限制内重新连接——我将以30秒为例——断开连接将被忽略。这样做的原因是,如果用户短暂失去连接,例如移动用户进入电梯,这是一个概念验证。

我决定用饼干做这个。我发现的逻辑是,当打开WebSocket时,它也会打开HttpSession。由此,我可以检查是否存在具有特定id的cookie。如果是,那么他们就不会被视为新用户。然而,为此,我需要能够在套接字关闭后将cookie的到期时间设置为30秒

我已经知道Cookie.setMaxAge()会这么做,但当我在服务器上的OnClose()方法中尝试时,服务器抛出了NullPointerException。这并不奇怪,因为我显然是在用户会话关闭后试图访问它。

那么,有办法做到这一点吗?

更新2月16日我决定在发送消息时尝试完全重置cookie。这在一定程度上是有效的,因为cookie是生成并添加到HttpSession中的,但在重新连接时,服务器会认为用户是全新的。所以,我认为我的问题是cookie没有发送给用户。

更新2在阅读了这个问题之后,我已经将cookie生成转移到了一个配置类中,该配置类在成功握手时调用。如果请求没有cookie,它将被视为一个全新的连接,并将其作为概念验证记录到系统控制台。我必须做的一件事是从一开始就延长饼干的使用寿命:目前,大概是10分钟。如果我不知道如何做到上面所说的,我会这么做。

2月19日更新我已经完全抛弃了cookie。查看我的解决方案。

我通过彻底抛弃cookie来解决这个问题。我刚刚展示了相关类中的方法;如果这还不够,我将编辑我的答案以包含完整的代码。

在配置类中,我得到请求的x-forwarded-for标头。这与客户端的IP地址相匹配,尤其是因为我的后端服务器位于代理之后。如果用户的IP地址在用户列表中,则会"刷新"用户的连接;否则,它们将被添加到列表中。在断开连接时,无论出于何种原因,用户都被标记为断开连接。

一个单独的ConnectionMonitor类实现Runnable接口,每10秒运行一次,并检查是否有客户端断开连接超过30秒。如果他们已经被删除,那么他们将从用户列表中删除。

MyConfigClass.modifyHandshake()

@Override
public void modifyHandshake(ServerEndpointConfig config,
                            HandshakeRequest request,
                            HandshakeResponse response)
{
    HttpSession theSession = (HttpSession) request.getHttpSession();
    config.getUserProperties().put(HttpSession.class.getName(), theSession);
    String ID = request.getHeaders().get("x-forwarded-for").get(0);
    if (ChatroomServerEndpoint.users.containsKey(ID))
    {
        // if this user isn't new, add them back onto the list
        User oldUser = ChatroomServerEndpoint.users.get(ID);
        System.out.println("An old user with " + ID + " has returned.");
        ChatroomServerEndpoint.users.remove(oldUser);
        ChatroomServerEndpoint.users.put(ID, oldUser);
        oldUser.toggleConnection(true);
        System.out.println(oldUser + ", " + ChatroomServerEndpoint.users.size() );
    }
    else
    {
        // add a new user to the list
        System.out.println("A new user with ID " + ID + " has arrived!");
        User newUser = new User(ID);
        ChatroomServerEndpoint.users.put(ID, newUser);
        System.out.println(newUser + ", " + ChatroomServerEndpoint.users.size() );
    }
    // put this ID into the configuration for proof of concept
    config.getUserProperties().put("newUser", ID);
}

ConnectionMonitor.updateUsers()在单独的线程中运行。

void updateUsers()
{
    for(String id : ChatroomServerEndpoint.users.keySet())
    {
        User theUser = ChatroomServerEndpoint.users.get(id);
        if (theUser.getStatus() == User.Connection.DISCONNECTED)
        {
            // get the time at which the user disconnected
            Calendar disconnectDate = theUser.getdisconnectionDate();
            // Calendar.getTime.getTime returns milliseconds,
            // so, multiply maxDisconnectTime by 1000 to see if the user has expired
            if (theDate.getTime().getTime() - disconnectDate.getTime().getTime() 
                    >= maxDisconnectTime * 1000 )
            {
                System.out.println(id + " has timed out");
                ChatroomServerEndpoint.users.remove(id);
            }
        }
    }
}

用户

public class User {

// the ID is the user's IP address
private String id;
// connection status
public enum Connection
{
    CONNECTED,
    DISCONNECTED
}
private Connection status;
// the time of disconnection
private Calendar disconnectionDate;
// each user needs a WebSocket Session to be able to send and receive messages
private Session userSession;
/** 
 * @return the id of this user
 */
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
/**
 * @return connection status
 */
public Connection getStatus() {
    return status;
}
public void setStatus(Connection status) {
    this.status = status;
}
public Calendar getdisconnectionDate() {
    return disconnectionDate;
}
public void setdisconnectionDate(Calendar disconnectionDate) {
    this.disconnectionDate = disconnectionDate;
}
/**
 * @return the userSession
 */
public Session getUserSession() {
    return userSession;
}
/**
 * @param userSession the userSession to set
 */
public void setUserSession(Session userSession) {
    this.userSession = userSession;
}
/**
 * @param newID the new ID of the user
 */
public User (String newID)
{
    this.id = newID;
    this.status = Connection.CONNECTED;
}
/**
 * Toggles the connection
 * @param toggle - if true, the user is connected
 */
public void toggleConnection(boolean toggle)
{
    if (toggle == false)
    {
        status = Connection.DISCONNECTED;
        disconnectionDate = Calendar.getInstance();
    }
    else
    {
        status = Connection.CONNECTED;
        disconnectionDate = Calendar.getInstance();
        disconnectionDate.add(Calendar.HOUR, 1);        // give an extra hour to prevent them being disconnected too soon
    }
}

}

最新更新