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 分钟前
MultiNet6 空闲崩溃:`EXCVADDR=0x8` 后又出现 `CORRUPT HEAP`
人工智能·后端·agent
武子康2 小时前
MultiNet7 每轮都 clean,ESP32-P4 内存为什么还在掉?
人工智能·后端·agent
超级架构师2 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core
陈随易2 小时前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员
IT_陈寒4 小时前
JavaScript的this坑人实录,这次我真的记下来了
前端·人工智能·后端
starzy19905 小时前
Scala类和对象:从构造器到样例类的完整指南
开发语言·后端·scala
梦影_5 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
考虑考虑5 小时前
mariadb数据库
数据库·后端·mariadb
明月_清风5 小时前
用自然语言操控真机:Google Artemis 移动端 AI Agent 上手与实践
人工智能·后端
怪我冷i5 小时前
Rust 的impl语法详解
开发语言·后端·rust