spring boot websocket集成

目录

1. maven配置

2. websocket配置

3. websocket集成

4. web-html调用

5. 测试

1. maven配置

# maven/pom.xml 中添加如下dependency:
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2. websocket配置

  创建wss作为websocket专用package, 新增配置类 WebSocketConfig.java


package com.example.springboottest.wss;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3. websocket集成

  在wss package下创建WebSocketHanddle类,用于websocket的连接管理&收发数据管理, 本代码中,将每次收到的消息,广播到所有在线的websocket上面,另外只传输了userId, 未对userId及session做绑定及验证逻辑,做聊天室或者其他功能,需要对其进行适度扩展。

package com.example.springboottest.wss;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@ServerEndpoint("/ws/channel/{userId}")
public class WebSocketHanddle {

    private static Map<String, Session> maps = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        String id = session.getId();
        log.info("onOpen sessionId:{}, this:{}, userId:{}", id, this.hashCode(), userId);
        maps.put(id, session);
    }

    @OnClose
    public void onClose(Session session){
        maps.remove(session.getId());
        log.info("onClose sessionId:{}, this:{}", session.getId(), this.hashCode());
    }

    @OnError
    public void onError(Session session, Throwable throwable){

        log.info("onError sessionId:{}, this:{}, {}", session.getId(), this.hashCode(), throwable.getMessage(), throwable);
    }
    @OnMessage
    public void onMessage(Session session, String text) throws IOException {

        log.info("onMessage sessionId:{}, this:{}, message:{}", session.getId(), this.hashCode(), text);

        session.getBasicRemote().sendText("服务端已经收到消息:"+ text);

        // 广播发送消息给所有在线用户
        broadCastMessage(session.getId(), text);
    }

    /**
     * 广播发送消息给在线用户
     * @param sendId
     * @param text
     * @throws IOException
     */
    public void broadCastMessage(String sendId, String text) throws IOException {

        for(String k : maps.keySet()){
            if(sendId.equals(k) == false){
                maps.get(k).getBasicRemote().sendText("推送消息:" + text);
            }
        }
    }


}

4. web-html调用

创建 test.html,浏览器页面进行测试

<!DOCTYPE HTML>
<html>
<head>
<title>web socket test</title>
</head>

<body>
    <input id="text" type="text" />
    <button onclick="send()">发送</button>
    <button onclick="close()">关闭</button>
    <div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/ws/channel/user_haha");
    } else {
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function() {
        show("error websocket");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        show("open websocket");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        show(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function() {
        show("close websocket");
    }

    //监听窗口关闭事件
    window.onbeforeunload = function() {
        websocket.close();
    }

    //将消息显示在网页上
    function show(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function close() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

5. 测试

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值