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 小时前
bignumber.js深度解析:驾驭任意精度计算的终极武器
前端·javascript·后端
服务端技术栈2 小时前
电商营销系统中的幂等性设计:从抽奖积分发放谈起
后端
你的人类朋友3 小时前
✍️Node.js CMS框架概述:Directus与Strapi详解
javascript·后端·node.js
面朝大海,春不暖,花不开3 小时前
自定义Spring Boot Starter的全面指南
java·spring boot·后端
HelloWord~3 小时前
SpringSecurity+vue通用权限系统
vue.js·spring boot
钡铼技术ARM工业边缘计算机4 小时前
【成本降40%·性能翻倍】RK3588边缘控制器在安防联动系统的升级路径
后端
wangjinjin1804 小时前
使用 IntelliJ IDEA 安装通义灵码(TONGYI Lingma)插件,进行后端 Java Spring Boot 项目的用户用例生成及常见问题处理
java·spring boot·intellij-idea
CryptoPP4 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
白宇横流学长4 小时前
基于SpringBoot实现的大创管理系统设计与实现【源码+文档】
java·spring boot·后端
草捏子5 小时前
状态机设计:比if-else优雅100倍的设计
后端