zoukankan      html  css  js  c++  java
  • C# 实现HTML5服务器推送事件

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

        因为如果需要保持前台数据的实时更新例如,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+"
    
    ");
                    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>
    

      前台截图:

  • 相关阅读:
    iPhone电话与短信相关代码小结
    时间都去哪儿了?开源一个统计iPhone上App运行时间和打开次数的小工具【iOS8已失效】
    分享一个仿网易新闻客户端iPhone版的标签式导航ViewController
    iOS推送小结(证书的生成、客户端的开发、服务端的开发)
    Argy1risMatrix1
    2019河南模考题
    撮箕2020-3-8
    数学符号md
    2014全国甲&2015福建-几何题
    零点
  • 原文地址:https://www.cnblogs.com/Evan-Pei/p/4798209.html
Copyright © 2011-2022 走看看