websocket实战

一:简介

  1. WebSocket协议通过在客户端和服务端之间提供全双工通信来进行Web和服务器的交互功能。
    在WebSocket应用程序中,服务器发布WebSocket端点,客户端使用url连接到服务器。建立连接后,服务器和客户端就可以互相发送消息。客户端通常连接到一台服务器,服务器接受多个客户端的连接。

二:实战

  1. pom.xml包

    <!--webSocket-->
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>
    
  2. @Configuration注入bean

    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
    
  3. 服务器代码

    @Slf4j
    @Component
    @ServerEndpoint(value = "/websocket/{year}")
    public class WebSocketController {
    
        //静态变量,用来记录当前在线连接数。应该把它设置成线程安全的。
        private static int onlineCount = 0;
    
        //concurrent包的线程安全set,用来存放每个客户端对应的MyWebSocket对象。
        private static CopyOnWriteArrayList<WebSocketController> webSocketServers = new CopyOnWriteArrayList<>();
    
        //与某个客户端连接对话,需要通过它来向客户端发送数据
        private Session session;
    
        /**
         * 初始化注入
         */
        private static WebSocketController webSocketController;
        @PostConstruct
        public void init(){
            webSocketController = this;
        }
    
        /**
         * @Author: guwenhai
         * @Description:    连接建立成功调用方法
         * @Date: 2020/12/1 9:56
         */
        @OnOpen
        public void OnOpen(Session session,@PathParam("year") Integer year){
            this.session = session;
            webSocketServers.add(this); //加入set中
            addOnlineCount();   //在线数+1
            log.info("有新连接加入!当前在线人数为:{}",getOnlineCount());
            try {
                dataInformation("1");
            } catch (Exception e){
                log.error("WebSocket IO异常");
                e.printStackTrace();
            }
        }
    
        /**
         * @Author: guwenhai
         * @Description:    连接关闭调用方法
         * @Date: 2020/12/1 10:00
         */
        @OnClose
        public void OnClose(){
            webSocketServers.remove(this);  //从set中删除
            subOnlineCount();   //在线人数-1
            log.info("有一个连接关闭!当前人数为:{}",getOnlineCount());
        }
    
        /**
         * @Author: guwenhai
         * @Description:    收到客户端消息后调用的方法
         * @Date: 2020/12/1 10:01
         */
        @OnMessage
        public void OnMessage(String message,Session session){
            log.info("来自客户端消息:{}",message);
            //群发消息
            for (WebSocketController item : webSocketServers) {
                try {
                    item.sendMessage(message);
                } catch (IOException e){
                    log.error("群发消息异常");
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * @Author: guwenhai
         * @Description:    错误
         * @Date: 2020/12/1 10:02
         */
        @OnError
        public void OnError(Session session,Throwable error){
            log.error("发送错误");
            error.printStackTrace();
        }
    
        public void sendMessage(String message) throws IOException{
            this.session.getBasicRemote().sendText(message);
        }
    
        public void sendMessage(Object obj) throws IOException,EncodeException{
            this.session.getBasicRemote().sendObject(obj);
        }
    
        public static synchronized int getOnlineCount(){
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount(){
            WebSocketController.onlineCount ++ ;
        }
    
        public static synchronized void subOnlineCount(){
            WebSocketController.onlineCount -- ;
        }
    
        /**
         * @Author: guwenhai
         * @Description:    自定义推送消息
         * @param type  类型:1-第一次连接推送消息,2-定时推送消息
         * @Date: 2020/12/1 10:09
         */
        public void dataInformation(String type){
            log.info("进入自定义推送消息");
            if(type.equals("1")){
                try {
                    StringWriter writer = new StringWriter();
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writeValue(writer,"数据消息---");
                    String message = writer.toString();
                    sendMessage(message);
                } catch (Exception e){
                    log.error("第一次握手---自定义推送消息异常");
                    e.printStackTrace();
                }
            } else if(type.equals("2")){
                for (WebSocketController item : webSocketServers) {
                    try {
                        StringWriter writer = new StringWriter();
                        ObjectMapper mapper = new ObjectMapper();
                        mapper.writeValue(writer,"数据消息---");
                        String message = writer.toString();
                        item.sendMessage(message);
                    } catch (IOException e){
                        log.error("自动推送---自定义推送消息异常");
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
  4. 客户端代码

    <!DOCTYPE HTML>
    <html>
    <head>
        <meta charset="utf-8">
        <title>测试webSocket</title>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script type="text/javascript">
            function WebSocketTest(){
                if ("WebSocket" in window){
                    console.log("您的浏览器支持 WebSocket!")
                    // 打开一个 web socket
                    var ws = new WebSocket("ws://localhost:7001/websocket/2021");
                    ws.onopen = function(){
                        // Web Socket 已连接上,使用 send() 方法发送数据
                        // ws.send("1");
                        console.log("数据发送中...")
                    };
                    ws.onmessage = function (evt){
                        var received_msg = evt.data;
                        console.log("数据已接收..." + received_msg)
                    };
                    ws.onclose = function(){
                        // 关闭 websocket
                        console.log("连接已关闭...")
                    };
                } else {
                    // 浏览器不支持 WebSocket
                    console.log("您的浏览器不支持 WebSocket!")
                }
            }
        </script>
    </head>
    <body>
    <div id="sse">
        <a href="javascript:WebSocketTest()">运行 WebSocket</a>
    </div>
    </body>
    </html>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值