欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET中ServerPush用法实例分析

程序员文章站 2023-12-22 19:35:04
本文实例讲述了asp.net中serverpush用法。分享给大家供大家参考。具体分析如下: 什么是serverpush,服务器向客户端“推送“,其实就是”长连接“ 只...

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

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

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

举个例子:

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

/// <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 tousername=@tousername",new sqlparameter("@tousername", me));
     if (dt.rows.count <= 0)
     {
      thread.sleep(500);//没找到,休息500ms再查询,这样避免对数据库的查询压力,和占用web服务器cpu资源
      continue;//下一次while
     }
     else
     {
      datarow row = dt.rows[0];
      long id = (long)row["id"];
      string fromusername = (string)row["fromusername"];
      string msg = (string)row["msg"];
      //查询完之后要删除消息,否则会出现死循环,不停的给页面输出同一个消息
      sqlhpler.executenonquery("delete from t_msgs where id=@id",new sqlparameter("@id",id));
      //创建一个匿名对象,将查询到的数据存到里面
      var data = new { fromusername = fromusername, msg = msg, id = id };
      string json = new javascriptserializer().serialize(data);//将匿名对象转换为json
      context.response.write(json);//将请求结果以json格式返回
      break;
     }
    }
   }
   else
   {
    throw new exception("action错误");
   }
}

<!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根据me查找发给me的消息
  success: function (data) {
   $('#ulmsg').append($('<li>' + data.fromusername + '对我说:' + data.msg + '</li>'));
   rev();//收到消息后再向服务器请求数据,再给我一条消息
  },
  error: function () {
   rev();
   //哪怕网络请求失败(比如用户网络故障),也再次发送请求
  }
 });
};
$(function () {
 //发送
 $('#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 },//根据用户输入的信息,传到服务端serverpush.ashx进行插入操作
   success: function (data) {
    if (data.status == 'ok') {//如果发送成功,
     $('#ulmsg').append($('<li>我对' + tousername + '说:' + msg + '</li>'));
     $('#msgcontext').val('');
    }
    else {
     alert('发送出错,返回报文无法识别');
    }
   },
   error: function () {
    alert('发送出错');
   }
  });
 });
 //登陆,接收数据
 $('#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根据me查找发给me的消息
   success: function (data) {
    $('#ulmsg').append($('<li>' + data.tousername + '对我说:' + data.msg + '</li>'));
   },
   error: function () {
    alert('接收失败');
   }
  });
 });*/
});
</script>
</head>
<body>
 发送人:<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="发送" /><br />
 聊天记录:<br />
 <ul id="ulmsg">
 </ul>
</body>
</html>

希望本文所述对大家的asp.net程序设计有所帮助。

上一篇:

下一篇: