WebSocket full-duplex communication SpringBoot implementation

[IT Laoqi 238] Get started with WebSocket full-duplex communication protocol in ten minutes_哔哩哔哩_bilibili [IT Laoqi 238] Get started with WebSocket full-duplex communication protocol in ten minutes, video playback volume 8348, barrage volume 23, likes Number of 318, number of coins tossed 157, number of favorites 257, number of reposts 30, video author IT Lao Qi, author profile Lao Qi's personal V: itlaoqi001 ~~Welcome to communicate, related videos: based on redis subscription messages and websocket technology Message push function, [websocket] [front-end] technology to ensure real-time front-end: websocket, 43 Spring Boot integrated WebSocket detailed explanation, SpringBoot WebSocket Echarts server pushes data to the client in real time, 12 minutes to complete a simple chat room based on websocket, springboot, vue . , How does WebFlux use SSE for server-side directional push, springboot quickly connects to webSocket (heartbeat connection)-RuoYi-Vue-Plus series of tutorials, SpringBoot series-Websocket real-time chat, what is the difference between socket and websocket? , [WebSocket communication] online chat room online chat system ___ build your own instant chat room WebSocket+Vue online chat room online chat system graduation source code case design https://www.bilibili.com/video/BV1Kd4y1w7JR/?spm_id_from= 333.337.search-card.all.click&vd_source=3b2d00a63e8d4ae7dea36274e5447a45

1. The backend pom.xml introduces dependencies

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

Second, the startup class injects Bean

@SpringBootApplication
public class TtSdemoApplication {

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

3. Write the WebSocket class

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();
    }
}

4. Write a test page

Write chat.html in the resource/static directory

<!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>

5. Communication test

Guess you like

Origin blog.csdn.net/qq_40421671/article/details/130870003