开发指南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();
    }
}
相关推荐
Eloudy3 小时前
互联网络设计过程中的一些 PPA 经验原则
网络·互联
网络小江11 小时前
上网第三十九课:TCP 的可靠性——滑动窗口、重传与拥塞控制
网络协议
国科安芯11 小时前
一颗当两颗用:ASC4T245S 的“两组独立 2 位 + 控制挂靠 VCCA“账
网络·电平转换·抗辐射·在轨服务
冯胤清11 小时前
《Jev-IDS:网络入侵检测一种系统模型》论文深度分析总结
网络
91刘仁德13 小时前
HTTP协议详解:从URL到HTTP服务器的完整实战
服务器·网络·笔记·网络协议·http
Sarapines Programmer13 小时前
【Wireshark】安装与使用指南
网络·测试工具·wireshark
可乐鸡翅yeah_15 小时前
hls.js 手动自定义 http 请求 loader,修改请求头实战
开发语言·前端·javascript·网络协议·http·ecmascript·m3u8在线
星夜夏空9915 小时前
网络编程(5)—— Reactor实现(v4)
网络
pt104317 小时前
CML网络仿真入门-2:使用CML模拟网络实验环境
运维·网络协议