代码改变世界

Server Sent Events传参

2022-10-12 15:48  若藜520  阅读(775)  评论(0编辑  收藏  举报

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会给每个前端建立的连接开启一个线程,所以即使多个页面调用同一个后端方法也不会有影响