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>

结果:

相关推荐
武子康19 分钟前
1.2GB 离线语音 Agent 真正值得复用的不是 908ms:四阶段职责 + 状态感知 Tool Schema + 可观测时间锚点
人工智能·后端·agent
掘金者阿豪20 分钟前
那些年踩过的 MySQL 迁移坑,这次终于不用绕了
后端
用户77139702070622 分钟前
深夜食堂:那个让我加班到凌晨的 ! 符号
后端
swipe23 分钟前
03|Axios 请求进了后端之后:Controller、Request、Response 是怎么接住它的?
前端·后端·全栈
swipe35 分钟前
02|从 `pnpm dev` 到 Spring Boot 启动:后端服务到底怎么跑起来?
前端·后端·全栈
网易云信36 分钟前
网易智企Data Agent实践入选信通院《智能体创新实践案例汇编》
人工智能·后端·线下活动
swipe1 小时前
01|前端人第一次打开 Spring Boot 项目,应该先看哪里?
前端·后端·全栈
薛定谔的悦1 小时前
一次充电桩 Modbus TCP 采集模块的踩坑实录
后端
jvmind_dev1 小时前
1c1g 容器莫名 OOM Killed?排查 Metaspace 持续增长与脚本引擎的坑
java·后端
geovindu1 小时前
go:Backtracking Algorithm
开发语言·后端·算法·golang·回溯算法