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();
            }
        }
    }
}
相关推荐
23.7 分钟前
【Java】char字符类型的UTF-16编码解析
java·开发语言·面试
怒放吧德德8 分钟前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端
indexsunny11 分钟前
互联网大厂Java面试实战:核心技术与业务场景深度解析
java·spring boot·hibernate·security·microservices·interview
是小蟹呀^15 分钟前
Java中的继承:从入门到精通
java·继承
SeanDe16 分钟前
Linux grep 命令用法详解
linux·服务器·网络
bearpping18 分钟前
怎么下载安装yarn
java
西门吹雪分身31 分钟前
JDK8之四大核心函数式接口
java·函数式接口
华科易迅41 分钟前
Spring AOP
java·后端·spring
架构师沉默44 分钟前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
zihao_tom1 小时前
Spring WebFlux:响应式编程
java·后端·spring