websocket的demo

1.引入依赖

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

2.前端代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <h1>12</h1>
<script>
    var websocket = null;
    if ('WebSocket' in window){
        websocket = new WebSocket('ws://localhost:8080/webSocket');
    }else {
        alert("不支持websocket ")
    }
    websocket.onopen = function (event){
        console.log('建立连接')
    }
    websocket.onclose = function (event){
        console.log('连接关闭')
    }
    websocket.onmessage = function (event){
        console.log('收到消息'+event.data)
    }
    websocket.onerror = function (){
        alert('错误')
    }
    window.onbeforeunload = function (){
        websocket.close();
    }
</script>
</body>
</html>

3.后端代码

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

@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSockets.add(this);
        System.out.println("webSocket消息,有新的连接 总数" + webSockets.size());
    }
    @OnClose
    public void onClose(){
        this.session = session;
        webSockets.remove(this);
        System.out.println("webSocket消息,连接断开 总数" + webSockets.size());
    }
    @OnMessage
    public void onMessage(String message){
            System.out.println("客户端消息" + message);
    }
    public void sendMessage(String message){
        for (WebSocket webSocket : webSockets) {
            System.out.println("广播消息" + message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
相关推荐
鼎讯信通8 小时前
风电光缆运维提质增效:G-4000A 光缆故障追踪仪破解风场巡检难题
运维·网络·数据库
fangdengfu1239 小时前
ES分析系统各个服务日志占用量
java·前端·elasticsearch
云烟成雨TD9 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
星越华夏9 小时前
ESP32-CAM图像传输项目说明文档
java·后端·struts·esp32
Multipath71210 小时前
无人区不掉线:多链路聚合路由,为环塔拉力赛筑起“空中通讯走廊”
网络·5g·安全·无人机·实时音视频
Jinkxs10 小时前
Java 跨域14-Java 与区块链(Hyperledger)集成
java·开发语言·区块链
晨曦中的暮雨11 小时前
Golang速通(Javaer版)
java·开发语言·后端·golang
o0麦嘎11 小时前
内网ip配置https
网络协议·tcp/ip·https
七老板的blog11 小时前
当 Spring StateMachine 遇见大模型:构建工业级 AI 写作流水线
java·人工智能·spring
云烟成雨TD12 小时前
Spring AI 1.x 系列【46】MCP Security 模块
java·人工智能·spring