SpringBoot搭建WebSocket初始化

1.java后端的maven添加websocket依赖

xml 复制代码
<!--        websocket依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.实例化ServerEndpointExporter对象,

这样才能自动调用@ServerEndpoint("/test")里面的方法

java 复制代码
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3.创建一个类,该类的功能是提供websocket服务

java 复制代码
/**
 * websocket服务
 */
@Component
@ServerEndpoint("/test")
public class WebsocketServer{

    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) {
        System.out.println("websocket已连接");
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("websocket已关闭");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("连接错误"+throwable);
    }
    //发送
    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("接收到消息:" + message);

        try {
            session.getBasicRemote().sendText("回应: " + message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

前端测试发起请求连接websocket

创建了一个html,控制台输出结果

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var ws=new WebSocket("ws://localhost:8080/test");
        ws.onopen=function(){
            console.log("连接成功");
            ws.send('6666');
        }
        ws.onclose=function(){
            console.log("连接关闭");
        }
        ws.onmessage=function(res){
            console.log(res);
        }
        ws.onerror=function(res){
            console.log(res);
        }
    </script>
</body>
</html>

结果:

相关推荐
Codebee15 分钟前
Qoder CLI 与 OneCode 平台深度整合技术实践:CLI委托驱动的开发范式革新
后端
码事漫谈21 分钟前
C++程序执行起点不是main:颠覆你认知的真相
后端
可观测性用观测云28 分钟前
玩转 Pipelines 之修正链路错误状态码
后端
码事漫谈30 分钟前
C++26:开启新纪元
后端
q***07141 小时前
Java实战:Spring Boot application.yml配置文件详解
java·网络·spring boot
龙卷风04051 小时前
深入理解Spring AI Alibaba多Agent系统:图结构驱动的智能协作
人工智能·后端
用户8356290780511 小时前
C# 高效生成 Word 表格:复杂表格创建实战指南
后端·c#
q***42821 小时前
SpringCloudGateWay
android·前端·后端
我是小妖怪,潇洒又自在1 小时前
springcloud alibaba搭建
后端·spring·spring cloud
l***74941 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud