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();
            }
        }
    }
}
相关推荐
wjcurry24 分钟前
我的实习日报
java·redis·mysql
9527华安28 分钟前
紫光同创FPGA实现AD7606数据采集转UDP网络传输,提供PDS工程源码和技术支持和QT上位机
网络·qt·fpga开发·udp·紫光同创·ad7606
北漂老男孩1 小时前
网络协议与系统架构分析实战:工具与方法全解
网络·网络协议·系统架构
___波子 Pro Max.1 小时前
http断点续传
网络·http
Johny_Zhao1 小时前
Ubuntu安装部署Zabbix网络监控平台和设备配置添加
linux·网络·mysql·网络安全·信息安全·云计算·apache·zabbix·shell·yum源·系统运维·itsm
我喜欢山,也喜欢海1 小时前
Jenkins Maven 带权限 搭建方案2025
java·jenkins·maven
明天更新1 小时前
Java处理压缩文件的两种方式!!!!
java·开发语言·7-zip
熙曦Sakura1 小时前
【Linux网络】HTTPS
linux·网络·https
铁锚1 小时前
一个WordPress连续登录失败的问题排查
java·linux·服务器·nginx·tomcat