萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET Server Push (長連接) 實作:HttpHandler + 輪詢模擬即時訊息

傳統輪詢模擬 Server Push:ASHX + JavaScript 循環請求

HTTP 協定無法主動推送,傳統方案採用**長輪詢**:客戶端發請求 → 伺服器 Hold 住連線直到有資料或逾時 → 回應 → 客戶端立即發下一個請求。

伺服端 HttpHandler (ServerPush.ashx)

public class ServerPush : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        string action = context.Request["action"];

        if (action == "send")  // 發送訊息
        {
            string from = context.Request["me"];
            string to = context.Request["toUserName"];
            string msg = context.Request["msg"];
            
            SqlHelper.ExecuteNonQuery(
                "INSERT INTO T_Msgs(FromUserName, ToUserName, Msg) VALUES(@From, @To, @Msg)",
                new SqlParameter("@From", from),
                new SqlParameter("@To", to),
                new SqlParameter("@Msg", msg));
            
            context.Response.Write("{\"Status\":\"ok\"}");
        }
        else if (action == "receive")  // 長輪詢接收
        {
            string me = context.Request["me"];
            
            while (true)
            {
                var dt = SqlHelper.ExecuteQuery(
                    "SELECT TOP 1 * FROM T_Msgs WHERE ToUserName=@To",
                    new SqlParameter("@To", me));
                
                if (dt.Rows.Count == 0)
                {
                    Thread.Sleep(500);  // 避免佔滿 CPU/DB
                    continue;
                }
                
                var row = dt.Rows[0];
                long id = (long)row["Id"];
                string from = (string)row["FromUserName"];
                string msg = (string)row["Msg"];
                
                // 讀取後立即刪除,避免重複推送
                SqlHelper.ExecuteNonQuery("DELETE FROM T_Msgs WHERE Id=@Id", 
                    new SqlParameter("@Id", id));
                
                var data = new { FromUserName = from, Msg = msg, Id = id };
                string json = new JavaScriptSerializer().Serialize(data);
                context.Response.Write(json);
                break;  // 結束此次長連接
            }
        }
        else
        {
            throw new Exception("action 錯誤");
        }
    }
    public bool IsReusable => false;
}

前端 JavaScript (jQuery)

var poll = function() {
    var me = $('#me').val();
    $.ajax({
        type: 'POST',
        url: 'ServerPush.ashx',
        data: { action: 'receive', me: me },
        success: function(data) {
            $('#ulMsg').append('
  • ' + data.FromUserName + '對我說:' + data.Msg + '
  • '); poll(); // 收到後立即發起下一輪 }, error: function() { setTimeout(poll, 2000); // 網路錯誤 2 秒後重試 } }); }; // 發送訊息 $('#btnSend').click(function() { $.post('ServerPush.ashx', { action: 'send', me: $('#me').val(), toUserName: $('#toUserName').val(), msg: $('#msgContext').val() }, function(res) { if (res.Status === 'ok') { $('#ulMsg').append('
  • 我對' + toUserName + '說:' + msg + '
  • '); $('#msgContext').val(''); } }); }); // 登入開始輪詢 $('#btnLogin').click(function() { poll(); $(this).prop('disabled', true); });

    架構缺陷與改進

    問題影響改進
    while(true) 佔用執行緒高併發下耗盡 ThreadPool改用 async/await + Task.Delay,或 SignalR
    資料庫輪詢壓力大每 500ms 查詢一次Redis Pub/Sub、SignalR Backplane、資料庫查詢通知
    無連線管理用戶關閉頁面仍佔用資源客戶端心跳、伺服端逾時清理
    單伺服器限制Web Farm 訊息不同步Redis/SQL Server 共享訊息佇列

    現代替代:SignalR / WebSocket / gRPC

    // ASP.NET Core SignalR Hub
    public class ChatHub : Hub
    {
        public async Task Send(string toUser, string msg)
        {
            await Clients.User(toUser).SendAsync("Receive", Context.UserIdentifier, msg);
        }
    }
    
    // 客戶端
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chatHub").build();
    connection.on("Receive", (from, msg) => { /* 顯示 */ });
    await connection.start();
    await connection.invoke("Send", "user2", "Hello");

    結論: 傳統輪詢適合簡單、低頻、單機場景。現代應用**強烈建議直接使用 SignalR**,自動協商 WebSocket/Server-Sent Events/長輪詢最佳傳輸,內建重連、群組、使用者映射、擴展性支援。

    copyright © 萬盛學電腦網 all rights reserved