• SpringBoot webSocket搭建示例


    POM文件引入:

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>

    开启websocket支持

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    /**
     * @ClassName WebSocketConfig
     * @Description 开启websocket
     * @Author Mr.bai
     * @Date 2020/5/15 15:25
     * @Version 1.0
     */
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    
    }

    WebSocket通道搭建

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    /**
     * @ClassName MyWebSocket
     * @Description TDDO
     * @Author Mr.bai
     * @Date 2020/5/15 15:23
     * @Version 1.0
     */
    @Component
    @Slf4j
    @ServerEndpoint("/websocket")
    public class MyWebSocket {
        /**
         * 与某个客户端的连接会话,需要通过它来给客户端发送数据
         */
        private Session session;
    
        /**
         * concurrent包的线程安全Set,用来存放每个客户端对应的WebSocket对象。
         */
        private static  CopyOnWriteArraySet<MyWebSocket> webSocketSet=new CopyOnWriteArraySet<>();
    
        /**
         *  建立连接成功
         * @param session
         */
        @OnOpen
        public void onOpen(Session session){
            this.session=session;
            webSocketSet.add(this);
            log.info("【websocket消息】 有新的连接,总数{}",webSocketSet.size());
        }
    
        /**
         * 连接关闭
         */
        @OnClose
        public void onClose(){
            this.session=session;
            webSocketSet.remove(this);
            log.info("【websocket消息】 连接断开,总数{}",webSocketSet.size());
        }
    
        /**
         * 接收客户端消息
         * @param message
         */
        @OnMessage
        public void onMessage(String message){
            log.info("【websocket消息】 收到客户端发来的消息:{}",message);
        }
    
        /**
         * 发送消息
         * @param message
         */
        public void sendMessage(String message){
            log.info("【websocket消息】 发送消息:{}",message);
            for (MyWebSocket webSocket:webSocketSet){
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    模拟控制层发送消息

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    /**
     * @ClassName SocketTest
     * @Description TDDO
     * @Author Mr.bai
     * @Date 2020/5/15 15:28
     * @Version 1.0
     */
    @RestController
    public class SocketTestController {
        @Resource
        private MyWebSocket webSocket;
    
        @GetMapping(value="/sendMsg/{msg}")
        public String sendMsg(@PathVariable String msg){
            webSocket.sendMessage(msg);
            return "推送的消息为:" + msg;
        }
    }

    Html测试代码

    <html>
     
        <head>
            <meta charset="utf-8" />
            <title></title>
        </head>
     
        <body>
            <input type="text" id="name" /><button onclick="send()">发送消息</button>
        </body>
        <script>
            var websocket = null;
            //判断浏览器是否支持websocket
            if('WebSocket' in window) {
                //实现化WebSocket对象
                websocket = new WebSocket("ws://localhost:8070/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(event) {
                console.log("websocket 通信发生错误");
            }
            window.onbeforeunload = function(event) {
                websocket.close();
            }
     
            //发送消息
            function send() {
                var message = document.getElementById('name').value;
                console.log("发送的消息:" + message)
                websocket.send(message);
            }
        </script>
     
    </html>

  • 相关阅读:
    过河卒 NOIp 2002 dp
    [POI2014]KUR-Couriers BZOJ3524 主席树
    【模板】可持久化线段树 1(主席树)
    EXPEDI
    取石子游戏 BZOJ1874 博弈
    【模板】文艺平衡树(Splay) 区间翻转 BZOJ 3223
    关于表白
    POJ 1951
    Codeforces 1032F Vasya and Maximum Matching dp
    Codeforces 1016F Road Projects
  • 原文地址:https://www.cnblogs.com/it-xiaoBai/p/12895470.html
Copyright © 2020-2023  润新知