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>

结果:

相关推荐
結城2 小时前
mybatisX的使用,简化springboot的开发,不用再写entity、mapper以及service了!
java·spring boot·后端
Bruk.Liu2 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio
星辰离彬3 小时前
Java 与 MySQL 性能优化:MySQL 慢 SQL 诊断与分析方法详解
java·spring boot·后端·sql·mysql·性能优化
q_19132846953 小时前
基于Springboot+Vue的办公管理系统
java·vue.js·spring boot·后端·intellij idea
2501_915106323 小时前
iOS性能调优实战:借助克魔(KeyMob)与常用工具深度洞察App瓶颈
websocket·网络协议·tcp/ip·http·网络安全·https·udp
陪我一起学编程4 小时前
关于nvm与node.js
vue.js·后端·npm·node.js
舒一笑4 小时前
基于KubeSphere平台快速搭建单节点向量数据库Milvus
后端
JavaBuild4 小时前
时隔半年,拾笔分享:来自一个大龄程序员的迷茫自问
后端·程序员·创业
周全全5 小时前
基于 Vue 和 Spring Boot 实现滑块验证码的机器验证
前端·vue.js·spring boot
一只叫煤球的猫5 小时前
虚拟线程生产事故复盘:警惕高性能背后的陷阱
java·后端·性能优化