zoukankan      html  css  js  c++  java
  • 基于HTTP的长轮询简单实现

    Web客户端与服务器之间基于Ajax(http)的常用通信方式,分为短连接与长轮询。

    短连接:客户端和服务器每进行一次HTTP操作,就建立一次连接,任务结束就中断连接。

    在长轮询机制中,客户端像传统轮询一样从服务器请求数据。然而,如果服务器没有可以立即返回给客户端的数据,则不会立刻返回一个空结果,

    而是保持这个请求等待数据到来(或者恰当的超时:小于ajax的超时时间),之后将数据作为结果返回给客户端。

    长轮询机制如下图所示:

    web客户端代码如下:

    //向后台长轮询消息
        function longPolling(){
            $.ajax({
                async : true,//异步
                url : 'longPollingAction!getMessages.action', 
                type : 'post',
                dataType : 'json',
                data :{},
                timeout : 30000,//超时时间设定30秒
                error : function(xhr, textStatus, thrownError) {
                    longPolling();//发生异常错误后再次发起请求
                },
                success : function(response) {
                    message = response.data.message;
                    if(message!="timeout"){
                        broadcast();//收到消息后发布消息
                    }
                    longPolling();
                }
            });
        }

    web服务器端代码如下:

    public class LongPollingAction extends BaseAction {
        private static final long serialVersionUID = 1L;
        private LongPollingService longPollingService;
        private static final long TIMEOUT = 20000;// 超时时间设置为20秒
    
        public String getMessages() {
            long requestTime = System.currentTimeMillis();
            result.clear();
            try {
                String msg = null;
    
                while ((System.currentTimeMillis() - requestTime) < TIMEOUT) {
                    msg = longPollingService.getMessages();
                    if (msg != null) {
                        break; // 跳出循环,返回数据
                    } else {
                        Thread.sleep(1000);// 休眠1秒
                    }
                }
                if (msg == null) {
                    result.addData("message", "timeout");// 超时
                } else {
                    result.addData("message", msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return SUCCESS;
        }
        
        public LongPollingService getLongPollingService() {
            return longPollingService;
        }
    
        public void setLongPollingService(LongPollingService longPollingService) {
            this.longPollingService = longPollingService;
        }
    
    }
  • 相关阅读:
    Flask把变量注册到模板中
    $.each与$(data).each区别
    【Python备忘】python判断文件和文件夹是否存在
    ISP图像质量自动化测试方法
    使用微软的(how-old.net)构建智能门店管理系统
    在virtualenv中安装libxml2和libxslt
    Python 装饰器学习以及实际使用场景实践
    tensorflow零起点快速入门(4) --入门常用API
    tensorflow零起点快速入门(3)
    树莓派和STM32通过USB和串口通信记录
  • 原文地址:https://www.cnblogs.com/bingyimeiling/p/9639721.html
Copyright © 2011-2022 走看看