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();
            }
        }
    }
}
相关推荐
情系淮思3 分钟前
客户端和服务器已成功建立 TCP 连接【输出解析】
服务器·网络·tcp/ip
Magnum Lehar14 分钟前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
sss191s15 分钟前
校招 java 面试基础题目及解析
java·开发语言·面试
异常君19 分钟前
MySQL 中 count(*)、count(1)、count(字段)性能对比:一次彻底搞清楚
java·mysql·面试
熙客41 分钟前
应用层协议:HTTPS
网络协议·https
wkj0011 小时前
QuaggaJS 配置参数详解
java·linux·服务器·javascript·quaggajs
阿琳a_1 小时前
前端对WebSocket进行封装,并建立心跳监测
前端·javascript·vue.js·websocket
异常君1 小时前
MyBatis 中 SqlSessionFactory 和 SqlSession 的线程安全性深度分析
java·面试·mybatis
crud1 小时前
Spring Boot 使用 spring-boot-starter-validation 实现优雅的参数校验,一文讲透!
java·spring boot
Dcs2 小时前
常见 GC 垃圾收集器对比分析
java