zoukankan      html  css  js  c++  java
  • springboot简单整合websocket

    <!-- websocket -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
    /**
     * WebSocket方法
     * @author Administrator
     *
     */
    @Component
    @ServerEndpoint("/webSocket")
    public class WebSocket {
    
        private Session session;
        
        private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
        
        /**
         * 开启
         * @param session
         */
        @OnOpen
        public void opOpen(Session session) {
            this.session = session;
            webSocketSet.add(this);
            System.out.println("有新的连接,总数:"+webSocketSet.size());
        }
        
        /**
         * 关闭
         */
        @OnClose
        public void onClose() {
            webSocketSet.remove(this);
            System.out.println("连接断开,总数:"+webSocketSet.size());
        }
        
        /**
         * 接受消息
         * @param message
         */
        @OnMessage
        public void onMessage(String message) {
            System.out.println("收到客户端消息:"+message);
        }
        
        /**
         * 发送消息
         * @param message
         */
        public void sendMessage(String message) {
            for (WebSocket webSocket : webSocketSet) {
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
        }
        
    }
    /**
     * 注入WebSocket
     * @author Administrator
     *
     */
    @Configuration
    public class WebSocketConfig {
        
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
    }
        if('WebSocket' in window){
              websocket = new WebSocket("ws://127.0.0.1:8080/......");
         }else{
             alert("该浏览器暂不支持websocket");
         }
        
        websocket.onopen = function(event){
            console.log("建立连接");
        }
        
        websocket.onclose = function(event){
            console.log("断开连接");
        }
        
        websocket.onmessage = function(event){
        String message = event.data //接受到消息后的逻辑
    } websocket.onerror = function(event){ alert("websocket通讯发生错误"); } window.onbeforeunload = function(){ websocket.close(); }
  • 相关阅读:
    linux文件系统初探--Day6
    Oracle 内置函数
    libusb常用函数说明(转)
    将多个blv格式的视频合并为一个mp4格式视频
    泰迪杯赛后总结
    如何下载B站上版权受限的视频?
    查看Ubuntu版本信息
    Visual Studio存在多个项目时启动项目的问题
    mfc | 初识mfc
    re | [ACTF新生赛2020]Splendid_MineCraft
  • 原文地址:https://www.cnblogs.com/ch94/p/14741500.html
Copyright © 2011-2022 走看看