自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

AJAX長輪詢之DotNet實(shí)現(xiàn)

開發(fā) 后端
今天和一個(gè)同事聊到了關(guān)于Web(傳統(tǒng))實(shí)時(shí)通訊的問題,其中包括輪詢、長輪詢、長連接。最后同事說長輪詢對(duì)與.net來說比較難以實(shí)現(xiàn)(不使用任何框架)。

今天和一個(gè)同事聊到了關(guān)于Web(傳統(tǒng))實(shí)時(shí)通訊的問題,其中包括輪詢、長輪詢、長連接。***同事說長輪詢對(duì)與.net來說比較難以實(shí)現(xiàn)(不使用任何框架)。

首先看一下什么是“長輪詢”!定義如下:

長輪詢:客戶端向服務(wù)器發(fā)送Ajax請求,服務(wù)器接到請求后hold住連接,直到有新消息才返回響應(yīng)信息并關(guān)閉連接,客戶端處理完響應(yīng)信息后再向服務(wù)器發(fā)送新的請求。

優(yōu)點(diǎn):在無消息的情況下不會(huì)頻繁的請求。

缺點(diǎn):服務(wù)器hold連接會(huì)消耗資源。

以上 “長輪詢” 定義是我在網(wǎng)上抄的哦!

那么是不是只要滿足以上所訴的內(nèi)容長輪詢是不是就成立呢?那就嘗試一下!

建立數(shù)據(jù)庫:

  1. if not exists(select 1 from  sys.databases where name='beidoudemo')  
  2. begin  
  3. Create Database beidoudemo  
  4. end  
  5. go  
  6.  
  7. use beidoudemo  
  8. go  
  9. if exists(select 1 from sysobjects where name='AjaxPolling' and type='u')  
  10. begin  
  11.   drop table AjaxPolling  
  12. end  
  13. go  
  14. Create table AjaxPolling  
  15. (  
  16.   id int identity Primary key,  
  17.   userName varchar(30) not null,  
  18.   passwordKey varchar(50) not null 

選用Jquery中的AJAX方法發(fā)送異步請求,前臺(tái)省了很多事情了!

具體代碼請看:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LongPolling.aspx.cs" Inherits="AjaxFinder.LongPolling" %>  
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>  
  7.     <title></title>  
  8.     <script type="text/javascript">  
  9.         var userID = 0;  
  10.         function SendXHR() {  
  11.             $.ajax({  
  12.                 type: "post"//AJAX請求類型  
  13.                 url: "LongPollingServer.ashx"//請求url  
  14.                 cache: false,  //無緩存  
  15.                 timeout: 1000 * 80,  //AJAX請求超時(shí)時(shí)間為60秒  
  16.                 data: { time: 60, userID: userID }, //參數(shù)time時(shí)間為最多等待(后臺(tái)保持)時(shí)間(60秒無論是否有數(shù)據(jù)立即返回),單位為秒。userID判斷詩句是否為新數(shù)據(jù)的標(biāo)識(shí)  
  17.                 success: function (data, textStatus) {  
  18.                     var obj = document.getElementById("NameDisplay");  
  19.                     //判斷返回成功還是失敗  如果后臺(tái)保持連接的時(shí)間一到并且沒有新數(shù)據(jù)就會(huì)返回fail開頭失敗的數(shù)據(jù)  
  20.                     if (data != null && data != "" && !(data.indexOf("fail") != -1)) {  
  21.                         var strarr = data.split(",");  
  22.                        // alert(strarr[0]);  
  23.                         userID = strarr[0];  
  24.                         obj.innerHTML = "親!有新用戶注冊哦!用戶名:" + strarr[1];  
  25.                     }  
  26.                     else {  
  27.                         obj.innerHTML = "親!暫無新用戶注冊哦";  
  28.                     }  
  29.                     SendXHR();//請求后立即發(fā)起AJAX請求  
  30.                 },  
  31.                 error: function (XMLHttpRequest, textStatus, errorThrown) {  
  32.                     //New Error do something  
  33.                     if (textStatus == "timeout") {  
  34.                         //超時(shí)間  
  35.                         SendXHR();  
  36.                     }  
  37.                 }  
  38.  
  39.             });  
  40.         }  
  41.         window.onload = function () {  
  42.             SendXHR();  
  43.         }  
  44.     </script>  
  45. </head>  
  46. <body>  
  47.     <form id="form1" runat="server">  
  48.     <div>  
  49.     </div>  
  50.         <div id="NameDisplay">  
  51.         </div>  
  52.     </form>  
  53. </body>  
  54. </html> 

前臺(tái)數(shù)據(jù)請求已經(jīng)準(zhǔn)備好了,接下來看一下后臺(tái)代碼實(shí)現(xiàn)。具體代碼如下:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Text;  
  6. using System.Net;  
  7. using System.Threading;  
  8. using System.Data;  
  9.  
  10. namespace AjaxFinder  
  11. {  
  12.     /// <summary>  
  13.     /// AJAX長輪詢后臺(tái)處理頁面  
  14.     /// 主要用于保持連接  
  15.     /// 有數(shù)據(jù)返回,無數(shù)據(jù)繼續(xù)保持連接超時(shí)返回  
  16.     /// author:bluescreen  
  17.     /// Date  :2013-03-14  
  18.     /// blog:http://www.cnblogs.com/bluescreen/  
  19.     /// 請不要關(guān)注代碼編寫規(guī)范等一些問題。這僅僅是一個(gè)DEMO  
  20.     /// 還存在諸多問題  
  21.     /// </summary>  
  22.     public class LongPollingServer : IHttpHandler  
  23.     {  
  24.  
  25.         public void ProcessRequest(HttpContext context)  
  26.         {  
  27.            /*  
  28.             context.Response.ContentType = "text/plain";  
  29.             context.Response.Write("Hello World");*/ 
  30.             int SendTime = 0;  //最多等待時(shí)間  
  31.             int userID = 0;    //上一次的用戶ID  
  32.             if (context.Request.Form["time"] != null&&context.Request.Form["time"].ToString()!="")  
  33.             {  
  34.                 SendTime =int.Parse(context.Request.Form["time"].ToString());//接收傳來的的后臺(tái)要保持時(shí)間  
  35.             }  
  36.             if (context.Request.Form["userID"] != null && context.Request.Form["userID"].ToString() != "")  
  37.             {  
  38.                 userID = int.Parse(context.Request.Form["userID"].ToString());  
  39.             }  
  40.             int i = 0;//計(jì)算超時(shí)時(shí)間(秒)  
  41.             while (true)  
  42.             {  
  43.                 Thread.Sleep(1000);//停留一千毫秒(1秒)  
  44.                 i++;  
  45.                 if (i < SendTime)  
  46.                 {  
  47.                     if (NameStr(userID) != "")  
  48.                     {  
  49.                         context.Response.Write(NameStr(userID));  
  50.                         break;  
  51.                     }  
  52.                 }  
  53.                 if (i == SendTime)  
  54.                 {  
  55.                     context.Response.Write("fail:無數(shù)據(jù)");  
  56.                     break;  
  57.                 }  
  58.             }  
  59.         }  
  60.         /// <summary>  
  61.         /// 獲得用戶名  
  62.         /// </summary>  
  63.         /// <param name="userID"></param>  
  64.         /// <returns></returns>  
  65.         private string NameStr(int userID)  
  66.         {  
  67.             string result = string.Empty;  
  68.             string Sqlstr = "select top 1 ID,UserName from AjaxPolling   Order by ID desc";  
  69.             DataSet ds = new DataSet();  
  70.             ds = SQLHelper.Query(Sqlstr, null);  
  71.             if (ds != null)  
  72.             {  
  73.                 if (ds.Tables[0].Rows.Count >= 1)  
  74.                 {  
  75.                     if (int.Parse(ds.Tables[0].Rows[0][0].ToString()) != userID || 0 ==int.Parse(ds.Tables[0].Rows[0][0].ToString()))  
  76.                     {  
  77.                         result = ds.Tables[0].Rows[0][0].ToString() + "," + ds.Tables[0].Rows[0][1].ToString();  
  78.                     }  
  79.                 }  
  80.             }  
  81.  
  82.             return result;  
  83.         }  
  84.         public bool IsReusable  
  85.         {  
  86.             get 
  87.             {  
  88.                 return false;  
  89.             }  
  90.         }  
  91.     }  

以上代碼經(jīng)過測試的確符合 “長輪詢” 的說法,那是不是可以說是長輪詢呢?各位大牛你們怎么看?

代碼下載:長輪詢AJAX之.net實(shí)現(xiàn)

原文鏈接:http://www.cnblogs.com/bluescreen/archive/2013/03/15/2960675.html

責(zé)任編輯:林師授 來源: 博客園
相關(guān)推薦

2011-05-18 13:28:46

jQueryPHPAJAX

2025-04-14 11:41:12

RocketMQ長輪詢配置

2023-11-28 08:49:01

短輪詢WebSocket長輪詢

2021-12-29 07:44:50

Dotnet 代碼系統(tǒng)

2025-04-27 02:00:00

實(shí)時(shí)通信Nacos服務(wù)端

2024-05-21 10:23:02

反射技術(shù).NET編程語言

2022-07-14 08:36:28

NacosApollo長輪詢

2012-08-01 14:16:27

IBMdW

2022-07-15 19:57:18

Cadence輪詢開源

2024-05-23 11:26:02

2009-05-20 14:49:16

ibmdwAjaxWeb開發(fā)

2012-04-27 10:00:43

jQuery插件

2021-07-07 08:01:51

命令行Dotnet Core控制臺(tái)

2021-02-26 12:37:39

WebSocketOkHttp連接

2024-05-27 09:52:57

反射技術(shù).NET動(dòng)態(tài)庫

2017-08-21 21:00:33

Java長圖文

2025-02-26 02:00:00

2009-06-26 13:46:13

Struts

2009-06-18 15:23:49

緩存控制器模式Ajax模式

2011-05-24 13:37:16

jQueryAjax
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)