代码改变世界

C# 实现HTML5服务器推送事件

2015-09-10 16:05  Evan.Pei  阅读(2257)  评论(0编辑  收藏  举报

为什么需要服务器推送事件:

    因为如果需要保持前台数据的实时更新例如,IM聊天,股票信息,

        1.可以在客户端不断地调用服务端的方法来获得新数据,但是这样会很消耗服务器资源,导致系统变慢!

       2 html5的新特性能在服务器直接发送最新数据到前台进行显示。

   先看后台的写法:WebForm8.aspx.cs

protected void Page_Load(object sender, EventArgs e)
        {
            
            Response.ContentType = "text/event-stream";
            Response.Expires = -1;
            while (true)
            {
                Response.Write("date1235:" + DateTime.Now+"\n\n");
                Thread.Sleep(2000);

                //向客户端发送当前的缓冲数据
                //如果你将Flush写的循环外面,将会等循环执行完后一起显示到前台,当然这个是死循环
                Response.Flush();
            }
            
        }

在看html的写法:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm8.aspx.cs" Inherits="WebApplication1.WebForm8" %>

<!DOCTYPE html><!--注意此处是HTML5的标识,写出这样代表目前用的html版本是5-->

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="result">
    
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    //HTML5 服务器推送事件
    function ServerSendClient() {
        if (typeof (EventSource) !== "undefined") {
            var source = new EventSource("WebForm8.aspx.cs");
            source.onmessage = function (event) {
                document.getElementById("result").innerHTML += event.data + "<br />";
            };
        }
        else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
        }
    }
    ServerSendClient();
</script>

  前台截图: