首页 > 网站 > 建站经验 > 正文

ASP.NET中Server!Push用法实例分析

2019-11-02 15:41:38
字体:
来源:转载
供稿:网友

 本文实例讲述了ASP.NET中ServerPush用法。分享给大家供大家参考。具体分析如下:

什么是ServerPush,服务器向客户端“推送“,其实就是”长连接“

只有浏览器请求服务器端,服务器端才给浏览器响应数据,不会主动向浏览器推送数据,这是一种安全考虑,也是提高服务器的性能考虑,如果服务器向浏览器主动推送数据,就要用到ServerPush等技术模拟实现。

举个例子:

通过两个页面互相发送消息实现,消息放到数据库。

1 2 3
好看的暴走漫画[www.62-6.com/1/baozoumanhua/]
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 /// <summary> /// ServerPush1 的摘要说明 /// </summary> public class ServerPush1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request["action"]; if (action == "send")//发送 { 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") //登陆,并持续查询、接收对方发过来的数据 { //做一个简单的例子,以ServerPush1.ashx?me=sean //请把发给sean的消息发给我一条 string me = context.Request["me"]; while (true) { DataTable dt = SQLHpler.ExecuteQuery("SELECT TOP 1 * FROM T_Msgs WHERE [email protected]",new SqlParameter("@ToUserName", me)); if (dt.Rows.Count <= 0) { Thread.Sleep(500);//没找到,休息500ms再查询,这样避免对数据库的查询压力,和占用WEB服务器
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表