http輪詢,長輪詢


輪詢,長輪詢

輪詢

  • 輪詢:客戶端定時向服務器發送Ajax請求,服務器接到請求后馬上返回響應信息並關閉連接。
  • 優點:后端程序編寫比較容易。
  • 缺點:請求中有大半是無用,浪費帶寬和服務器資源。
  • 實例:適於小型應用。

長輪詢

  • 長輪詢:客戶端向服務器發送Ajax請求,服務器接到請求后hold住連接,直到有新消息才返回響應信息並關閉連接,客戶端處理完響應信息后再向服務器發送新的請求。
  • 優點:在無消息的情況下不會頻繁的請求,耗費資源小。
  • 缺點:服務器hold連接會消耗資源,返回數據順序無保證,難於管理維護。
  • 實例:WebQQ、Hi網頁版、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;
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM