SpringBoot3集成WebSocket

标签:WebSocket,Session,Postman。

一、简介

WebSocket通过一个TCP连接在客户端和服务器之间建立一个全双工、双向的通信通道,使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据,在WebSocket的API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

基于Postman工具的WebSocket交互

复制代码
Connected to ws://127.0.0.1:8088/web/socket/msg

Handshake Details
Request URL: http://127.0.0.1:8088/web/socket/msg
Request Method: GET
Status Code: 101 

Request Headers
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: 5Qrs8JeRLsiY9G/PRJUocQ==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8088

Response Headers
Upgrade: websocket
Connection: upgrade
Sec-WebSocket-Accept: E3aFw2bBzxByPCynmQ7lZ+7BgsU=
Sec-WebSocket-Extensions: permessage-deflate;client_max_window_bits=15

二、工程搭建

1、工程结构

2、依赖管理

starter-websocket的依赖中,涉及到spring框架中两个关系较为密切的组件,分别是websocketmessaging组件。

xml 复制代码
<!--WebSocket-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

三、WebSocket用法

1、示意图

在下面的案例中,大致模拟这样一个流程,三个客户端分别和服务端建立连接,然后进行客户端之间的会话通信。

2、API参考

这里通过4个核心的方法注解,分别处理会话的不同动作,比如连接的建立和关闭,通信交互和错误处理;在实际的应用场景中,需要在通信方法中设计更多的指令来应对不同的业务场景。

java 复制代码
@ServerEndpoint("/web/socket/msg")
public class MsgWebSocket {

    private static final  ConcurrentHashMap<String,Session> sessions = new ConcurrentHashMap<>();

    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 建立连接调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        String userId = session.getRequestParameterMap().get("userId").get(0);
        // 加入Set中
        sessions.put(userId,session);
        // 在线数增加
        onlineCount.getAndIncrement();
        log.info("session-{},online-count-{}",session.getId(),onlineCount.get());
    }

    /**
     * 客户端消息处理的方法
     */
    @OnMessage
    public void sendMsg(Session sender,String message) throws Exception {
        MsgDTO dto = JSONUtil.toBean(message, MsgDTO.class);
        Session receiver = sessions.get(dto.getUserId());
        if (receiver != null) {
            receiver.getBasicRemote().sendText(dto.getMsg());
        }
    }

    /**
     * 关闭连接调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        String userId = session.getRequestParameterMap().get("userId").get(0);
        // 从Set中删除
        sessions.remove(userId);
        // 在线数减少
        onlineCount.getAndDecrement();
        log.info("session-{},down-line-count-{}",session.getId(),onlineCount.get());
    }

    /**
     * 发生错误调用的方法
     */
    @OnError
    public void onError(Session session, Throwable throwable) throws Exception {
        log.error("Web Stock Error", throwable);
        session.getBasicRemote().sendText(throwable.getMessage());
    }
}

测试效果图:注意这里使用的是postman最新版本。

四、源码参考

复制代码
文档仓库:
https://gitee.com/cicadasmile/butte-java-note

源码仓库:
https://gitee.com/cicadasmile/butte-spring-parent
相关推荐
2501_9160074724 分钟前
绕过 Xcode?使用 Appuploader和主流工具实现 iOS 上架自动化
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_9160137425 分钟前
使用 Windows 完成 iOS 应用上架:Appuploader对比其他证书与上传方案
websocket·网络协议·tcp/ip·http·网络安全·https·udp
一只帆記19 小时前
HTTP、WebSocket、SSE 对比
websocket·http
Sparkxuan19 小时前
封装WebSocket
前端·websocket
2501_9159214320 小时前
高敏感应用如何保护自身不被逆向?iOS 安全加固策略与工具组合实战(含 Ipa Guard 等)
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_9151063221 小时前
App 上线后还能加固吗?iOS 应用的动态安全补强方案实战分享(含 Ipa Guard 等工具组合)
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915918411 天前
iOS 项目怎么构建稳定性保障机制?一次系统性防错经验分享(含 KeyMob 工具应用)
websocket·网络协议·tcp/ip·http·网络安全·https·udp
2501_915909061 天前
从零搭建到 App Store 上架:跨平台开发者使用 Appuploader与其他工具的实战经验
websocket·网络协议·tcp/ip·http·网络安全·https·udp
LuckyRich11 天前
【websocket】安装与使用
网络·websocket·网络协议
椰椰椰耶2 天前
[网页五子棋][匹配模块]实现胜负判定,处理玩家掉线
java·开发语言·spring boot·websocket·spring