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

    WebSocket跟常规的http协议的区别和优缺点这里大概描述一下

    一、websocket与http 

    http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能发送信息。http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息。即每一个request对应一个response。长链接是在一定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。 
    WebSocket是HTML5中的协议, 他是为了解决客户端发起多个http请求到服务器资源浏览器必须要经过长时间的轮训问题而生的,他实现了多路复用,他是全双工通信。在webSocket协议下客服端和浏览器可以同时发送信息。

    二、HTTP的长连接与websocket的持久连接

    HTTP1.1的连接默认使用长连接(persistent connection),

    即在一定的期限内保持链接,客户端会需要在短时间内向服务端请求大量的资源,保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。

      在一个TCP连接上可以传输多个Request/Response消息对,所以本质上还是Request/Response消息对,仍然会造成资源的浪费、实时性不强等问题。

    如果不是持续连接,即短连接,那么每个资源都要建立一个新的连接,HTTP底层使用的是TCP,那么每次都要使用三次握手建立TCP连接,即每一个request对应一个response,将造成极大的资源浪费。

      长轮询,即客户端发送一个超时时间很长的Request,服务器hold住这个连接,在有新数据到达时返回Response

    websocket的持久连接  只需建立一次Request/Response消息对,之后都是TCP连接,避免了需要多次建立Request/Response消息对而产生的冗余头部信息。

    Websocket只需要一次HTTP握手,所以说整个通讯过程是建立在一次连接/状态中,而且websocket可以实现服务端主动联系客户端,这是http做不到的。

    三、websocket实现

    springboot集成websocket项目目录:

    pom添加依赖

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

    因涉及到js连接服务端,所以也写了对应的html,这里集成下thymeleaf模板,前后分离的项目这一块全都是前端做的

    <!-- springboot集成thymeleaf的起步依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    properties配置文件

    #服务端口号
    server.port=8080
    server.servlet.context-path=/websocketdemo
    
    #视图层控制
    spring.mvc.view.prefix=classpath:/templates/
    spring.mvc.view.suffix=.html
    #spring.mvc.static-path-pattern=/static/**
    #关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true
    spring.thymeleaf.cache=false
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.encoding=UTF-8
    spring.resources.chain.strategy.content.enabled=true
    spring.resources.chain.strategy.content.paths=/**

    自定义WebSocketServer,使用底层的websocket方法,提供对应的onOpen、onClose、onMessage、onError方法

    添加webSocketConfig配置类

    //开启WebSocket支持
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
        }
    }

    添加webSocketServer服务端类

    /**
     * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
     *                 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
     */
    
    @ServerEndpoint("/websocket/{sid}")
    @Component
    public class WebSocketServer {
        // 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
        // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
        private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    
        // 与某个客户端的连接会话,需要通过它来给客户端发送数据
        private Session session;
    
        // 接收sid
        private String sid = "";
    
        /**
         * 连接建立成功调用的方法
         */
        @OnOpen
        public void onOpen(Session session, @PathParam("sid") String sid) {
            this.session = session;
            webSocketSet.add(this); // 加入set中
            addOnlineCount(); // 在线数加1
            System.out.println("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
            this.sid = sid;
            try {
                sendMessage("连接成功");
            } catch (IOException e) {
                System.out.println("websocket IO异常");
            }
        }
    
        /**
         * 连接关闭调用的方法
         */
        @OnClose
        public void onClose() {
            webSocketSet.remove(this); // 从set中删除
            subOnlineCount(); // 在线数减1
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
    
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message 客户端发送过来的消息
         */
        @OnMessage
        public void onMessage(String message, Session session) {
            System.out.println("收到来自窗口" + sid + "的信息:" + message);
            // 群发消息
            for (WebSocketServer item : webSocketSet) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         *
         * @param session
         * @param error
         */
        @OnError
        public void onError(Session session, Throwable error) {
            System.out.println("发生错误");
            error.printStackTrace();
        }
    
        /**
         * 实现服务器主动推送
         */
        public void sendMessage(String message) throws IOException {
            this.session.getBasicRemote().sendText(message);
        }
    
        /**
         * 群发自定义消息
         */
        public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
            System.out.println("推送消息到窗口" + sid + ",推送内容:" + message);
            for (WebSocketServer item : webSocketSet) {
                try {
                    // 这里可以设定只推送给这个sid的,为null则全部推送
                    if (sid == null) {
                        item.sendMessage(message);
                    } else if (item.sid.equals(sid)) {
                        item.sendMessage(message);
                    }
                } catch (IOException e) {
                    continue;
                }
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            WebSocketServer.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            WebSocketServer.onlineCount--;
        }
    
        public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
            return webSocketSet;
        }
    }

    添加对应的controller

    @Controller
    public class websocketController {
        
        //跳转到websocket界面
        @RequestMapping(value="/websocket")
        public String websocket(Model model) {
            return "websocket";
        }
    }

    提供websocket.html页面

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>websocketDemo</title>
    </head>
    <body>
        Welcome<br/>
        <input id="text" type="text" />
        <button onclick="send()">Send</button>
        <button onclick="closeWebSocket()">Close</button>
        <div id="message"></div>
        
    <script type="text/javascript">
        var websocket = null;
        
        //判断当前浏览器是否支持WebSocket
        if('WebSocket' in window){
            websocket = new WebSocket("ws://localhost:8080/websocketdemo/websocket/chat");
        }else{
            alert('Not support websocket');
        }    
        //连接发生错误的回调方法
        websocket.onerror = function(){
            setMessageInnerHTML("error");
        };     
        //连接成功建立的回调方法
        websocket.onopen = function(event){
            setMessageInnerHTML("open");
        };      
        //接收到消息的回调方法
        websocket.onmessage = function(){
            setMessageInnerHTML(event.data);
        };     
        //连接关闭的回调方法
        websocket.onclose = function(){
            setMessageInnerHTML("close");
        };       
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function(){
            websocket.close();
        };       
        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML){
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        } 
        //关闭连接
        function closeWebSocket(){
            websocket.close();
        }  
        //发送消息
        function send(){
            var message = document.getElementById('text').value;
            websocket.send(message);
        }
    </script>
    </body>
    </html>

    效果图:

  • 相关阅读:
    linux下mysql数据导入到redis
    redis常用api
    springboot2.0+mybatis多数据源集成
    斐波那契数列(递归、非递归算法)
    从尾到头打印链表
    docker学习笔记:简单构建Dockerfile【Docker for Windows】
    python3+OpenGL环境配置
    【python库安装问题解决】UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 121: invalid start byte
    DA-GAN技术【简介】【机器通过文字描述创造图像】
    洛谷 P2045 方格取数加强版【费用流】
  • 原文地址:https://www.cnblogs.com/qiantao/p/12891913.html
Copyright © 2011-2022 走看看