2021-03-03

SpringBoot简单整合WebSocket

1、准备工作

1.1、引入jar包 一般springboot 项目中,starter都不用写version ​

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<!--websocket支持包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
    <version>2.4.3</version>
</dependency>
<!--lang工具包-->
<dependency>
  <groupId>commons-lang</groupId>
  <artifactId>commons-lang</artifactId>
  <version>2.6</version>
</dependency>

2、新增WebSocket配置文件

2.1、新建WebSocketConfig 实现WebSocketConfigurer接口类

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry
                //添加自定义webSocketHandler , 第二个参数websocket注册路径
                .addHandler(new MyWebSocketHandler(), "/websocket/*")
                .addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
                        String uri = String.valueOf(serverHttpRequest.getURI());
                        String orderId = uri.substring(uri.lastIndexOf("/")+1);
                        map.put(WebSocketConstant.ORDER_ID, orderId);
                        return true;
                    }
​
                    @Override
                    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
                        System.out.println("握手之后");
                    }
                });
    }
}


如图所示 需要重写registerWebSocketHandlers方法,根据方法名可得知这是一个注册WebSocketHandler的方法,所以我们得自定义一个MyWebSocketHandler类进行注册

2.2、新建MyWebSocketHandler,实现WebSocketHandler接口

public class MyWebSocketHandler implements WebSocketHandler {
    private Map<String,WebSocketSession> WEBSOCKET_LIST = new HashMap<String,WebSocketSession>(16);
    //建立连接后
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        String orderId = String.valueOf(webSocketSession.getAttributes().get(WebSocketConstant.ORDER_ID));
        if(!StringUtils.isBlank(orderId)){
            WEBSOCKET_LIST.put(orderId , webSocketSession);
        }
    }
​
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        String msgPayLoad = String.valueOf(webSocketMessage.getPayload());
        System.out.println(msgPayLoad);
        //简单点,就给自己返回
        webSocketSession.sendMessage(new TextMessage("这是一个哈哈哈哈"));
    }
​
    public void sendToUserMessage(String to , String content) throws IOException {
        TextMessage textMessage = new TextMessage(content);
        WebSocketSession webSocketSession = WEBSOCKET_LIST.get(to);
        if(webSocketSession!=null && webSocketSession.isOpen()){
            webSocketSession.sendMessage(textMessage);
        }
    }
​
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
​
    }
​
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        String orderId = String.valueOf(webSocketSession.getAttributes().get(WebSocketConstant.ORDER_ID));
        WEBSOCKET_LIST.get(orderId).close();
    }
​
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

 

可以看到需要重写里面的方法

   //这个是指连接开启后
    void afterConnectionEstablished(WebSocketSession var1) throws Exception;
​
    //监听消息
    void handleMessage(WebSocketSession var1, WebSocketMessage<?> var2) throws Exception;
​
    //出现错误时
    void handleTransportError(WebSocketSession var1, Throwable var2) throws Exception;
​
    //连接关闭后
    void afterConnectionClosed(WebSocketSession var1, CloseStatus var2) throws Exception;
​
    boolean supportsPartialMessages();

2.3、WebSocketConfig中的addInterceptors是什么作用呢?

Interceptors都知道是个拦截器,实际上就是拦截握手,对webSocket连接前进行一个自定义处理

 

3、新建HTML页面对WebSocket进行一个测试

3.1、使用thymeleaf,引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.2、在resouce中的template目录下新建html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket测试</title>
</head>
<body>
<input type="text" id="orderId"/><br/>
<input type="button" value="连接" onclick="connection()"/>
<input type="button" value="发送" onclick="sendMessage()"/>
</body>
<script type="text/javascript">
    let webSocket = null;
    function connection(){
        let orderId = document.getElementById("orderId").value;
        if("WebSocket" in window){
            webSocket = new WebSocket("ws://"+document.location.host+"/websocket/"+orderId)
        } else {
            console.log("当前浏览器不支持websocket")
        }
​
        webSocket.onopen = function (){
            console.log("打开链接了");
        };
        webSocket.onmessage = function (event){
            console.log("收到消息"+event.data);
        };
​
        webSocket.onerror = function(){
            console.log("ws出错了");
        }
​
        webSocket.onclose = function(){
            console.log("ws关闭了");
        }
​
        window.onbeforeunload = function(){
            if(webSocket!=null){
                webSocket.close();
            }
        }
    }
​
    function sendMessage(){
        webSocket.send("我是前端,我收到消息了");
    }
​
</script>
</html>

 

新建跳转页面controller

4、测试

4.1、启动项目 浏览器访问 http://localhost:9532/index/ws

随意输入一串数字,点击连接,会在控制台打印打开连接了!

 

4.2、点击发送

前端发送

 

后端收到:

 

 

我后端会响应这段文字

 

这里的webSocketSession是指当前的webSocket对象,他会发送到自己的页面

 

前端收到后段返回

 

5、到这里,一个简单的websocket整合springboot就搭建好了!具体的功能得根据自己的业务进行处理!

最后:新人一个,瞎写的,大佬不要喷我

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值