http polling, long polling

Polling, long polling

polling

  • Polling: The client periodically send Ajax request to the server, the server returns a response immediately after receiving the request message and closes the connection.
  • Pros: the back-end programming easier.
  • Cons: There are more than half of the request is useless and a waste of bandwidth and server resources.
  • Example: suitable for small applications.

Long polling

  • Long polling: Ajax client sends a request to the server, the server hold live connection upon request, does not return until a new message response information and close the connection, the client sends a new response information after their request to the server.
  • Advantages: not frequently request message without a case, small consumption of resources.
  • Cons: server hold the connection will consume resources, to ensure that no data is returned order, difficult to manage and maintain.
  • Examples: WebQQ, Hi web version, Facebook IM.
//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;
    }

}

Guess you like

Origin www.cnblogs.com/frankltf/p/11410831.html