Asp.Net+SSE示例

  Asp.Net+SSE示例,将下面代码存储到x.aspx中,访问x.aspx可以看到效果,如果修改过文件名,注意修改EventSource参数

Asp.Net+SSE示例

<%@ Page Language="C#" AutoEventWireup="true"  %>
<%@ Import Namespace="System.Threading" %>
<script runat="server">
    public static int count = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["op"] == "es")
        {
            Response.Clear();
            Response.ContentType = "text/event-stream";
            Response.CacheControl = "no-cache";
            while (true)
            {
                count++;
                Response.Write("data:" + count + " - "+DateTime.Now.ToString()+"\n\n");
                Response.Flush();
                Thread.CurrentThread.Join(1000);
            }
        }
    }
</script>
<html>
    <head><title>Asp.Net+SSE示例</title></head>
    <body>
        
        <div id="result"></div>  
        <script>
            if (typeof (EventSource) !== "undefined") {
                var source = new EventSource("x.aspx?op=es");
                source.onmessage = function (event) {
                    document.getElementById("result").innerHTML += event.data + "<br>";
                };
            }
            else {
                document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 server-sent 事件...";
            }
        </script>  
    </body>
</html>

 


原创文章,转载请注明出处:Asp.Net+SSE示例

评论(0)Web开发网
阅读(113)喜欢(0)Asp.Net/C#