WebSocket全双工通信SpringBoot实现

【IT老齐238】十分钟上手WebSocket全双工通信协议_哔哩哔哩_bilibili【IT老齐238】十分钟上手WebSocket全双工通信协议, 视频播放量 8348、弹幕量 23、点赞数 318、投硬币枚数 157、收藏人数 257、转发人数 30, 视频作者 IT老齐, 作者简介 老齐的个人V: itlaoqi001 ~~欢迎前来交流,相关视频:基于redis订阅消息和websocket技术实现的消息推送功能,【websocket】【前端】保证前端实时性的技术:websocket,43 Spring Boot整合WebSocket详解,SpringBoot WebSocket Echarts 服务器实时向客户端推送数据,12分钟搞定基于websocket,springboot,vue的简单聊天室。,WebFlux如何使用SSE做服务端的定向推送,springboot快速接入webSocket(心跳连接)- RuoYi-Vue-Plus系列教程,SpringBoot系列-Websocket 实时聊天,socket和websocket有什么区别?,【WebSocket通信】网络聊天室在线聊天系统___搭建自己的即时聊天室 WebSocket+Vue网络聊天室在线聊天系统毕业源码案例设计https://www.bilibili.com/video/BV1Kd4y1w7JR/?spm_id_from=333.337.search-card.all.click&vd_source=3b2d00a63e8d4ae7dea36274e5447a45

一、后端pom.xml引入依赖

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

二、启动类注入Bean

@SpringBootApplication
public class TtSdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TtSdemoApplication.class, args);
    }
   
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

三、编写WebSocket类

package com.zj.ttsdemo.controller;

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

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * Created by
 *
 * @Author: JoyceZhang
 * @Date: 2023/05/25/15:28
 * @Description:
 */
@Slf4j
@ServerEndpoint(value="/websocket")
@Component
public class Websocket {
    private static Session[] sessionContainer = new Session[2];
    /**
     * A,B与服务器建立连接
     */
    @OnOpen
    public void onOpen(Session session) {
        if (sessionContainer[0] == null && sessionContainer[1] == null) {
            sessionContainer[0] = session;
            log.info("a连接成功");
        } else if (sessionContainer[0] != null && sessionContainer[1] == null) {
            sessionContainer[1] = session;
            log.info("b连接成功");
        } else {
            log.info("连接失败");
        }
    }

    /**
     * 链接关闭
     */
    @OnClose
    public void onClose(Session session) {
        for(int i=0;i<sessionContainer.length;i++){
            if(sessionContainer[i] == session){
                sessionContainer[i] = null;
                log.info((i==0?"a":"b")+"断开连接");
            }
        }
    }

    /**
     * 得到另一个session对象
     */
    private Session getOtherSession(Session session) {
       for(int i = 0; i<sessionContainer.length;i++){
           if(session == sessionContainer[i]){
               log.info("获取到另一个session");
               return sessionContainer[(i==0?1:0)];
           }
       }
         return null;
    }


    /**
     * 向另一个session发送消息
     */
    @OnMessage
    public void sendMessage(String message,Session session) throws IOException{
        Session otherSession = this.getOtherSession(session);
        log.info("发送消息"+message+"到"+(otherSession==sessionContainer[0]?"a":"b"));
        otherSession.getBasicRemote().sendText(message);
    }

    /**
     * 异常处理
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
}

四、编写测试页面

在resource/static目录下编写chat.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<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:8083/websocket");
    }
    else{
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("服务器通信故障");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("与服务器通信成功");
    }

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

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

    //监听窗口关闭事件,当窗口关闭时,主动去关闭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>

五、通信测试

猜你喜欢

转载自blog.csdn.net/qq_40421671/article/details/130870003
今日推荐