SpringBoot集成WebSocket以及可能遇到的部分问题的解决方式

1.集成

1.1 首先导入pom依赖

核心是@ServerEndpoint这个注解。这个注解是Javaee标准里的注解,tomcat7以上已经对其进行了实现,如果是用传统方法使用tomcat发布项目,只要在pom文件中引入javaee标准即可使用。

 <dependency>
     <groupId>javax</groupId>
     <artifactId>javaee-api</artifactId>
     <version>7.0</version>
     <scope>provided</scope>
 </dependency>

如果使用springboot的内置tomcat时,就不需要引入javaee-api了,spring-boot已经包含了。使用springboot的websocket功能要引入springboot的websocket组件。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
   <version>1.3.5.RELEASE</version>
</dependency>

1.2 添加websocket配置类

首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。要注意,如果使用独立的servlet容器,而不是直接使用springboot的内置容器,就不要注入ServerEndpointExporter,因为它将由容器自己提供和管理。

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

}

1.3 后端代码部分

@ServerEndpoint(value = "/websocket")
@Component
public class MyWebSocket {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}

使用springboot的唯一区别是要@Component声明下,而使用独立容器是由容器自己管理websocket的,但在springboot中连容器都是spring管理的。

虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,所以可以用一个静态set保存起来。

1.4 前端代码部分

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

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

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

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

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

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

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

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }

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

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

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

2.本人集成websocket时遇到的问题以及解决方法

2.1 无法正常启动项目

在demo中集成websocket时一切正常,但当移植到工作中的正式项目上时启动报错,无法正常启动,是因为将websocket实现类放到了controller目录下,额外新建一个websocket目录,将实现类放进去即可正常启动

2.2 无法与前端建立连接

2.2.1 使用ServerEndpointExporter但没用使用外置tomcat容器

错误原因:ServerEndpointExporter需要外置tomcat容器运行环境,但平常我们都是使用SpringBoot内置tomcat,导致ServerEndpointExporter在运行时一直报错。

解决方案:在pom.xml文件中,排除SpringBoot自带的嵌入tomcat,添加外置的tomcat依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<!-- 移除嵌入式tomcat插件 -->
	<exclusions>
    	<exclusion>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- 添加外置的tomcat依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
2.2.2 使用拦截器或过滤器但没有对请求放行

错误原因:使用拦截器或过滤器但没有对请求放行,特别是使用Spring Security或Shiro,很容易遗忘放行请求路径

解决方案:在相应的配置文件中放行请求路径

filterMap.put("/websocket/**", "anon");//开放webSocket路径

2.3 解决在web页面中动态口令场景下的连接与断开问题

在页面维持期间,动态口令需要一直不断的向前端推送实时口令,但是何时断开以及是谁断开就成了一个问题
解决方式如下:
创建一个WebSocketConnectStatusController类,
在前端发起websocket请求前,由前端生成一个特定的长度的key,
(1)进入动态口令页面,首先调用doIn接口并传入key,该key由前端保留备用;后端使用静态map来存放key,并将value设为0。
(2)建立连接,同时在session中传入上一步生成的key

@RestController
@RequestMapping("/webSocketConnectStatus")
public class WebSocketConnectStatusController {

    public static Map<String, String> map = new HashMap<>();

    @GetMapping("/doIn")
    @ApiOperation(value = "doIn方法")
    public String doIn(String key){

        //System.out.println("调用了doIn---");

        map.put(key,"0");

        return "开始获取动态码了";
    }

    @GetMapping("/doOut")
    @ApiOperation(value = "doOut方法")
    public String doOut(String key){

        //System.out.println("调用了doOut---");

        map.put(key,"1");

        return "改完状态了,动态码获取结束";
    }

}

(3)当用户离开页面时,调用doOut接口,并传入之前保留的本次连接的key,后端将静态map中对应key的value更新为1,此时后端不再向前端推送新的口令,循环结束。

后端推送消息的具体逻辑如下:

	@OnMessage
    public void onMessage(String message, Session session) {

        String key = session.getQueryString();//获取session中的key

        try {

            while ("0".equals(WebSocketConnectStatusController.map.get(key))){
                Thread.sleep(1000);//每秒推送一次
                sendMessage("生成你的动态码");
            }

            WebSocketConnectStatusController.map.remove(key);//清空本次链接的key

        } catch (IOException e) {
            System.out.println("IO异常");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

只有当循环结束时才能正常断开连接,否则会报IO异常

(4)断开连接

  • 37
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SpringBoot集成WebSocket是指在SpringBoot项目中使用WebSocket技术来实现后台向前端推送信息的功能。通过集成WebSocket,可以实现实时的双向通信,使后端能够主动向前端推送消息。 要实现SpringBoot集成WebSocket,首先需要创建一个SpringBoot项目,并引入WebSocket依赖。可以在pom.xml文件中添加以下依赖: ``` <!-- WebSocket dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.7.12</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.7.12</version> </dependency> ``` 然后,需要在SpringBoot的配置类上添加@EnableWebSocket注解,启用WebSocket功能。同时,可以创建一个WebSocket处理器类,用于处理WebSocket连接和消息的处理逻辑。 在启动项目后,可以通过访问http://localhost:8081/demo/toWebSocketDemo/{cid}来跳转到页面,然后就可以和WebSocket进行交互了。通过WebSocket连接,后台可以向前端主动推送消息,实现实时的双向通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot 集成WebSocket详解](https://blog.csdn.net/qq_42402854/article/details/130948270)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值