实现WebSocket心跳机制,以及超过30分钟无活动自动关闭会话的功能

实现WebSocket心跳机制,以及超过30分钟无活动自动关闭会话的功能,涉及到后端和前端的协作。下面分别介绍后端(使用Spring WebFlux)和前端如何实现这一机制。

后端实现(Spring WebFlux)

在Spring WebFlux中,你可以定期发送心跳消息(例如,使用ping消息)来维持连接。同时,你需要追踪最后一次活动时间,如果超过30分钟无活动,则关闭会话。

  1. 心跳消息发送

WebSocketHandler的实现中,你可以通过定时发送ping消息来实现心跳。使用Flux.interval创建一个定期执行的Flux,并发送ping消息。

@Override
public Mono<Void> handle(WebSocketSession session) {
    Flux<WebSocketMessage> heartBeat = Flux.interval(Duration.ofSeconds(15))  // 每15秒发送一次心跳
            .map(tick -> session.pingMessage(DataBufferFactory -> DataBufferFactory.allocateBuffer(0)));

    Mono<Void> output = session.send(heartBeat);

    Mono<Void> input = session.receive()  // 处理接收到的消息
            .doOnNext(message -> {
                // 更新最后活动时间
            })
            .then();

    return Mono.zip(input, output).then();
}
  1. 活动追踪和超时处理

你可以定义一个变量来追踪最后一次活动时间。每次接收到消息时更新这个时间。同时,你可以使用一个定时器来检查是否已经超过30分钟无活动。

AtomicLong lastActivityTime = new AtomicLong(System.currentTimeMillis());

Flux<WebSocketMessage> timeoutChecker = Flux.interval(Duration.ofMinutes(1))
    .flatMap(tick -> {
        long inactiveDuration = System.currentTimeMillis() - lastActivityTime.get();
        if (inactiveDuration > Duration.ofMinutes(30).toMillis()) {
            // 超过30分钟无活动,可以关闭会话
            return Flux.just(session.close(CloseStatus.NORMAL.withReason("Inactive for more than 30 minutes")));
        } else {
            return Flux.empty();  // 无操作
        }
    });

Mono<Void> output = session.send(Flux.merge(heartBeat, timeoutChecker));

前端实现

前端需要实现两部分逻辑:一是响应心跳消息,二是处理连接超时关闭。

  1. WebSocket心跳响应

前端WebSocket客户端需要能够处理后端发送的心跳ping消息,并据此保持连接。

let socket = new WebSocket("ws://example.com/ws");
socket.onmessage = function(event) {
    // 处理服务器发送的消息
};

// 处理Ping消息,维持连接
socket.onping = function(event) {
    // 可以发送Pong消息回应,或不做任何操作
};
  1. 超时关闭处理

前端还需要能够处理超过30分钟无数据交换时的情况。这通常通过设置一个定时器实现,每次收到消息时重置定时器。

let timeoutInterval = 30 * 60 * 1000;  // 30分钟
let timeoutTimer;

function resetTimeout() {
    clearTimeout(timeoutTimer);
    timeoutTimer = setTimeout(() => {
        socket.close();
        alert("WebSocket closed due to inactivity.");
    }, timeoutInterval);
}

socket.onopen = resetTimeout;
socket.onmessage = resetTimeout;
socket.onping = resetTimeout;  // 如果前端能收到ping消息,也应重置定时器

通过上述方法,你可以在客户端和服务器之间实现一个心跳机制,以及在超过一定时间无活动时自动关闭WebSocket连接的功能。

相关推荐

  1. 大模型: 流式实现方式

    2024-03-31 06:56:07       56 阅读
  2. SpringBoot 中实现订单30分钟自动取消策略

    2024-03-31 06:56:07       60 阅读
  3. SpringBoot 中实现订单30分钟自动取消策略

    2024-03-31 06:56:07       63 阅读
  4. SpringBoot 中实现订单30分钟自动取消策略

    2024-03-31 06:56:07       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-31 06:56:07       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-31 06:56:07       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-31 06:56:07       87 阅读
  4. Python语言-面向对象

    2024-03-31 06:56:07       96 阅读

热门阅读

  1. 当代深度学习模型介绍--卷积神经网络(CNNs)

    2024-03-31 06:56:07       41 阅读
  2. Github 2024-03-30 开源项目日报 Top10

    2024-03-31 06:56:07       45 阅读
  3. Swagger文档转html和pdf格式_亲测成功

    2024-03-31 06:56:07       40 阅读
  4. 【极简主义的深度学习】01 概览深度学习

    2024-03-31 06:56:07       32 阅读
  5. Spring Boot 使用详解

    2024-03-31 06:56:07       35 阅读
  6. 数据仓库的发展历程

    2024-03-31 06:56:07       37 阅读
  7. Docker常用命令

    2024-03-31 06:56:07       42 阅读