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();
            }
        }
    }
}
相关推荐
清风徐来QCQ9 小时前
javaScript(map,ref,?,forEach,watch)
java·前端·javascript
7***n759 小时前
Java构建工具
java·开发语言
Dandelion____z9 小时前
AI 驱动业务的致命风险:如何用架构设计守住安全底线?
java·大数据·人工智能·spring boot·aigc·jboltai
Q***K559 小时前
Kotlin与Java互操作指南
java·开发语言·kotlin
“αβ”9 小时前
MySQL库的操作
linux·服务器·网络·数据库·c++·mysql·oracle
_星辰大海乀10 小时前
TCP 协议
网络·网络协议·tcp/ip·tcp
星空的资源小屋10 小时前
永久删除文件利器:Permadelete
java·javascript·人工智能
2201_7578308710 小时前
Stream的终结方法
java·服务器·前端
今天没ID10 小时前
Java 数组进阶操作
java
卷到起飞的数分10 小时前
5.MyBatis持久(dao)层框架
java·数据库·mybatis