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

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

后端实现(Spring WebFlux)

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

  1. 心跳消息发送

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

java 复制代码
@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分钟无活动。

java 复制代码
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消息,并据此保持连接。

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

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

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

javascript 复制代码
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连接的功能。

相关推荐
一颗青果16 分钟前
HTTP协议详解
linux·网络·网络协议·http
晚枫歌F8 小时前
TCP协议详解
网络·网络协议·tcp/ip
秋4278 小时前
防火墙基本介绍与使用
linux·网络协议·安全·网络安全·架构·系统安全
sweet丶8 小时前
扩展了解DNS放大攻击:原理、影响与防御
网络协议·安全
科技块儿10 小时前
我应该如何选择并使用IP数据库评估不同地区的定位精度(⊙_⊙?)
网络·网络协议·tcp/ip
万粉变现经纪人12 小时前
如何解决 pip install SSL 报错 ValueError: check_hostname requires server_hostname 问题
网络·python·网络协议·beautifulsoup·bug·ssl·pip
松涛和鸣12 小时前
DAY42 SQLite3 : Dictionary Import and Data Query Implementation with C Language
linux·c语言·数据库·单片机·网络协议·sqlite
hdsoft_huge14 小时前
Java 实现高效查询海量 geometry 及 Protobuf 序列化与天地图前端分片加载
java·前端·状态模式
Channon_15 小时前
双网卡绑定、软PRP、硬PRP技术解析:区别与联系
物联网·网络协议·可用性测试
仰科网关16 小时前
化工厂SCADA系统OPC DA数据转Modbus TCP接入全厂监控平台项目案例
网络·网络协议·modbus·snmp·opc da·协议转换