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();
            }
        }
    }
}
相关推荐
微小的鱼1 分钟前
Linux的渲染与显示系统链路
android·java·linux
严肃小白兔43 分钟前
Cloudflare 更新 API Token 管理:从最小权限到自动化凭据安全
网络·安全·自动化
若亦_1 小时前
Java中关于this的三种用法
java·开发语言·intellij-idea
山甫aa1 小时前
锁一篇搞定:乐观锁、悲观锁、CAS、数据库锁与分布式锁【从零开始的 Web 后端学习】
java·数据库·分布式·后端·学习·web
软件技术NINI1 小时前
基于SpringBoot和Vue的博物馆预约平台管理系统的设计与实现
java·毕业设计·毕设
独泪了无痕11 小时前
探索Pinyin4j-Java中的拼音转换利器
java·后端
道尔柯南12 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
kingx313 小时前
Bugku 3122 谷歌小恐龙题解:纯离线逆向 Vault 的 AES-GCM 加密资源(附 Python 解密器)
java·逆向·ctf·bugku·aes-gcm
Linux-lucky13 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
DevOpenClub15 小时前
职教高考控制线 API:招生类别枚举、筛选与空分数含义
java·数据库·高考