Server Sent Events前端给后端传递参数

 

前端建立连接

<script>


    var time = guid();
   
    var url="/Home/sse/?guid="+time+"&t=10000";
    var source = new EventSource(url);
    // 默认事件 message 可以使用 onmessage 回调
    source.onmessage = function (event) {
        var data = event.data;
        document.getElementById("content").innerHTML += data + "<br/>";
    //source.close(); 关闭连接
    }
  

    function guid() {
    function S4() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
</script>

 

前端完整代码


@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
    <p><a onclick="tests();" class="btn btn-primary btn-lg">test</a></p>
    <div id="content"></div>
</div>

<div class="row">
    <div class="col-md-4">
        <h2>Getting started</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Get more libraries</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p>
    </div>
    <div class="col-md-4">
        <h2>Web Hosting</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p>
    </div>
</div>

@section scripts{
    

<script>


    var time = guid();
   
    var url="/Home/sse/?guid="+time+"&t=10000";
    var source = new EventSource(url);
    // 默认事件 message 可以使用 onmessage 回调
    source.onmessage = function (event) {
        var data = event.data;
        document.getElementById("content").innerHTML += data + "<br/>";
    //source.close(); 关闭连接
    }
  

    function guid() {
    function S4() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    }
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
</script>

}

View Code

 

后端

        //Server-Sent Event
        public void Sse()
        {
            System.Threading.Thread.Sleep(1000);

            Random random = new Random();
            
            //设置HTTP MIME 类型,不缓存页面
            Response.ContentType = "text/event-stream";
            Response.CacheControl = "no-cache";
            string guid = string.IsNullOrEmpty(Request.QueryString["guid"]) ? "null" : Request.QueryString["guid"].ToString();
            var t = string.IsNullOrEmpty(Request.QueryString["t"]) ? "0" : Request.QueryString["t"].ToString();
           
            if(Response.IsClientConnected)
            {
                try
                {
                    
                    string data = SseData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " from http://www.cnblogs.com/ainijiutian/ guid:"+ guid +" "+ Request.UserAgent);
                    Response.Write(data);
                    Response.Flush();

                    System.Threading.Thread.Sleep(random.Next(500, 5000));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            };

            Response.End();
            Response.Close();
        }

        //SSE data
        private string SseData(string data)
        {
            return "data:" + data + "\n\n";
        }

 

 

 

后端完整代码:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            
            //Thread thread = new Thread(Sss);
            //thread.Start(Guid.NewGuid().ToString());
            return View();
        }

        public ActionResult Test(string guid)
        {
           
            return new EmptyResult();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        
        //Server-Sent Event
        public void Sse()
        {
            System.Threading.Thread.Sleep(1000);

            Random random = new Random();
            
            //设置HTTP MIME 类型,不缓存页面
            Response.ContentType = "text/event-stream";
            Response.CacheControl = "no-cache";
            string guid = string.IsNullOrEmpty(Request.QueryString["guid"]) ? "null" : Request.QueryString["guid"].ToString();
            var t = string.IsNullOrEmpty(Request.QueryString["t"]) ? "0" : Request.QueryString["t"].ToString();
           
            if(Response.IsClientConnected)
            {
                try
                {
                    
                    string data = SseData(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " from http://www.cnblogs.com/ainijiutian/ guid:"+ guid +" "+ Request.UserAgent);
                    Response.Write(data);
                    Response.Flush();

                    System.Threading.Thread.Sleep(random.Next(500, 5000));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            };

            Response.End();
            Response.Close();
        }

        //SSE data
        private string SseData(string data)
        {
            return "data:" + data + "\n\n";
        }
    }
}

View Code

 

Server Sent Events会给每个前端建立的连接开启一个线程,所以即使多个页面调用同一个后端方法也不会有影响

原文地址:http://www.cnblogs.com/lidaying5/p/16784770.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性