开发指南148-WebSocket-后端

首先上组件

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.2.5.RELEASE</version>
</dependency>

然后实现:

复制代码
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer

最关键的是

复制代码
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws")
            .setAllowedOrigins(allowedOrigins.split(","))
            // 握手阶段把 URL 上的 token 存进 session attributes(鉴权兜底通道)
            .addInterceptors(tokenHandshakeInterceptor())
            .withSockJS()
            .setSessionCookieNeeded(false)
            // SockJS 层心跳 25s:SockJS 在 http 轮询降级时靠它保活
            .setHeartbeatTime(25_000)
            .setTaskScheduler(heartbeatScheduler())
            .setDisconnectDelay(30_000);
}

其中必须写明具体Origins,写* 一定前端跨域失败(前端底层自身问题)

实现

复制代码
public class WebSocketAuthInterceptor implements ChannelInterceptor 进行token校验

实现后台发送类:

复制代码
public class LocalStompPublisher 

其中:

复制代码
public String send(PushEnvelope envelope) {
    try {
        String destination = envelope.getDestination();

        // 投递前先看有没有订阅者
        int subscribers = subscriptionTracker.count(destination);
        if (subscribers == 0) {
            CommonsUtil.debugLog("destination=" + destination + " 当前无订阅者");
        } else {
            messagingTemplate.convertAndSend(destination, envelope.getPayloadJson());
            CommonsUtil.debugLog("本地投递成功 destination=" + destination);
        }
        return "";
    } catch (Exception e) {
        CommonsUtil.recordLog(e);
        return "ERROR:" + e.getMessage();
    }
}
相关推荐
如夏倾城14 小时前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
张小姐的猫17 小时前
【基于 WebSocket 的多用户网页五子棋】—— 认识第三方库Websocketpp
网络·websocket·网络协议
张小姐的猫17 小时前
【基于 WebSocket 的多用户网页五子棋】—— 游戏匹配对战设计
websocket·网络协议·游戏
LightBreeze200217 小时前
IS-IS 基本概念详解——报文类型、地址结构与网络拓扑
网络·lsp·路由协议·net·is-is
我不会起名字32221 小时前
WebSocket 停机与在线状态:Shutdown 返回后还需要清理什么
redis·后端·websocket·go·即时通讯·im·故障排查
小乖写代码1 天前
提交注册验证 · WhatsApp /v2/register
android·网络·账号注册
多弗朗皮卡丘1 天前
网络基础:数据链路层与其他协议或技术
linux·网络·tcp/ip
我不会插花弄玉2 天前
9.数据链路层【由浅入深-网络】
网络
我不会起名字3222 天前
仅 Web 主动 ping:30 秒读超时与各平台保活
前端·后端·websocket·go·即时通讯·im·故障排查
进击的荆棘2 天前
Linux网络——网络基础概念
linux·运维·服务器·网络