HTTP 協定無法主動推送,傳統方案採用**長輪詢**:客戶端發請求 → 伺服器 Hold 住連線直到有資料或逾時 → 回應 → 客戶端立即發下一個請求。
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;
}
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 共享訊息佇列 |
// 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/長輪詢最佳傳輸,內建重連、群組、使用者映射、擴展性支援。