本文實(shí)例講述了ASP.NET中ServerPush用法。分享給大家供大家參考。具體分析如下:
什么是ServerPush,服務(wù)器向客戶端“推送“,其實(shí)就是”長(zhǎng)連接“
只有瀏覽器請(qǐng)求服務(wù)器端,服務(wù)器端才給瀏覽器響應(yīng)數(shù)據(jù),不會(huì)主動(dòng)向?yàn)g覽器推送數(shù)據(jù),這是一種安全考慮,也是提高服務(wù)器的性能考慮,如果服務(wù)器向?yàn)g覽器主動(dòng)推送數(shù)據(jù),就要用到ServerPush等技術(shù)模擬實(shí)現(xiàn)。
舉個(gè)例子:
通過(guò)兩個(gè)頁(yè)面互相發(fā)送消息實(shí)現(xiàn),消息放到數(shù)據(jù)庫(kù)。
/// summary>
/// ServerPush1 的摘要說(shuō)明
/// /summary>
public class ServerPush1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
string action = context.Request["action"];
if (action == "send")//發(fā)送
{
string me = context.Request["me"];
string toUserName = context.Request["toUserName"];
string msg = context.Request["msg"];
SQLHpler.ExecuteNonQuery("INSERT INTO T_Msgs(FromUserName,ToUserName,Msg) VALUES(@FromUserName,@ToUserName,@Msg)", new SqlParameter("@FromUserName", me),
new SqlParameter("@ToUserName", toUserName),
new SqlParameter("@Msg", msg));
context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "ok" }));
}
else if (action == "receive")
//登陸,并持續(xù)查詢、接收對(duì)方發(fā)過(guò)來(lái)的數(shù)據(jù)
{
//做一個(gè)簡(jiǎn)單的例子,以ServerPush1.ashx?me=sean
//請(qǐng)把發(fā)給sean的消息發(fā)給我一條
string me = context.Request["me"];
while (true)
{
DataTable dt = SQLHpler.ExecuteQuery("SELECT TOP 1 * FROM T_Msgs WHERE ToUserName=@ToUserName",new SqlParameter("@ToUserName", me));
if (dt.Rows.Count = 0)
{
Thread.Sleep(500);//沒找到,休息500ms再查詢,這樣避免對(duì)數(shù)據(jù)庫(kù)的查詢壓力,和占用WEB服務(wù)器CPU資源
continue;//下一次while
}
else
{
DataRow row = dt.Rows[0];
long id = (long)row["Id"];
string fromUserName = (string)row["FromUserName"];
string msg = (string)row["Msg"];
//查詢完之后要?jiǎng)h除消息,否則會(huì)出現(xiàn)死循環(huán),不停的給頁(yè)面輸出同一個(gè)消息
SQLHpler.ExecuteNonQuery("DELETE FROM T_Msgs WHERE Id=@Id",new SqlParameter("@Id",id));
//創(chuàng)建一個(gè)匿名對(duì)象,將查詢到的數(shù)據(jù)存到里面
var data = new { FromUserName = fromUserName, Msg = msg, Id = id };
string json = new JavaScriptSerializer().Serialize(data);//將匿名對(duì)象轉(zhuǎn)換為json
context.Response.Write(json);//將請(qǐng)求結(jié)果以json格式返回
break;
}
}
}
else
{
throw new Exception("action錯(cuò)誤");
}
}
!DOCTYPE html>
html xmlns="http://www.w3.org/1999/xhtml">
head>
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
title>/title>
script type="text/javascript" src="jquery-1.8.3.min.js">/script>
script type="text/javascript">
var rev = function () {
var mine = $('#me').val();
$.ajax({
type: 'post', url: 'serverPush1.ashx',
data: { action: 'receive', me: mine },//傳給serverPush.ashx根據(jù)me查找發(fā)給me的消息
success: function (data) {
$('#ulMsg').append($('li>' + data.FromUserName + '對(duì)我說(shuō):' + data.Msg + '/li>'));
rev();//收到消息后再向服務(wù)器請(qǐng)求數(shù)據(jù),再給我一條消息
},
error: function () {
rev();
//哪怕網(wǎng)絡(luò)請(qǐng)求失?。ū热缬脩艟W(wǎng)絡(luò)故障),也再次發(fā)送請(qǐng)求
}
});
};
$(function () {
//發(fā)送
$('#btnSend').click(function () {
var myName = $('#me').val();
var toUserName = $('#toUserName').val();
var msg = $('#msgContext').val();
$.ajax({
type: 'post', url: 'serverPush1.ashx',
data: { action: 'send', me: myName, toUserName: toUserName, msg: msg },//根據(jù)用戶輸入的信息,傳到服務(wù)端ServerPush.ashx進(jìn)行插入操作
success: function (data) {
if (data.Status == 'ok') {//如果發(fā)送成功,
$('#ulMsg').append($('li>我對(duì)' + toUserName + '說(shuō):' + msg + '/li>'));
$('#msgContext').val('');
}
else {
alert('發(fā)送出錯(cuò),返回報(bào)文無(wú)法識(shí)別');
}
},
error: function () {
alert('發(fā)送出錯(cuò)');
}
});
});
//登陸,接收數(shù)據(jù)
$('#btnLogin').click(function () {
rev();
$(this).attr("disabled", "disabled");
});
/*
$('#btnLogin').click(function () {//接收
var mine = $('#me').val();
$.ajax({
type: 'post', url: 'serverPush1.ashx',
data: { action: 'receive', me: mine },
//傳給serverPush.ashx根據(jù)me查找發(fā)給me的消息
success: function (data) {
$('#ulMsg').append($('li>' + data.toUserName + '對(duì)我說(shuō):' + data.msg + '/li>'));
},
error: function () {
alert('接收失敗');
}
});
});*/
});
/script>
/head>
body>
發(fā)送人:input type="text" id="me" />input type="button" id="btnLogin" value="登陸" style=""/>br />
接收人:input type="text" id="toUserName" />br />
輸入消息:input type="text" id="msgContext" />input type="button" id="btnSend" value="發(fā)送" />br />
聊天記錄:br />
ul id="ulMsg">
/ul>
/body>
/html>
希望本文所述對(duì)大家的asp.net程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Asp.net的服務(wù)器推技術(shù) (Server Push)
- ASP.NET中Global和URLReWrite用法
- ASP.NET中Application全局對(duì)象用法實(shí)例淺析
- ASP.NET中母版頁(yè)和shtml實(shí)例入門
- ASP.NET檢測(cè)到不安全 Request.Form 值解決方案匯總
- asp.net開發(fā)微信公眾平臺(tái)之驗(yàn)證消息的真實(shí)性