Javascript 在需要时维护持久连接和推送事件

Javascript 在需要时维护持久连接和推送事件,javascript,c#,server-sent-events,Javascript,C#,Server Sent Events,我正在尝试解决服务器发送的事件。我必须从不同的服务器和用户响应推送事件。 我有消费者在localhost:A上,服务器在localhost:B 我只想在单击“推送事件”按钮时推送事件。 并通过事件通道建立持久连接 localhostA js function contentLoaded() { var source = new EventSource('https://localhost:44398/home/message', { withCre

我正在尝试解决服务器发送的事件。我必须从不同的服务器和用户响应推送事件。 我有消费者在
localhost:A
上,服务器在
localhost:B

我只想在单击“推送事件”按钮时推送事件。 并通过事件通道建立持久连接

localhostA js

    function contentLoaded() {
        var source = new EventSource('https://localhost:44398/home/message', {
            withCredentials: true
        });
        //var ul = $("#messages");
        source.onmessage = function (e) {

            var li = document.createElement("li");
            var returnedItem = e.data;
            li.textContent = returnedItem;
            $("#messages").append(li);
        }

        source.onerror = function (e) {
            console.log(e);
        }
    };
<script>
    var sendEvent = function () {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/home/message?id=4");
        xhr.onload = function (e) {
            console.log(e);
        }
        xhr.onerror = function (e) {
            console.log(e);
        }
        xhr.send();
    }
</script>
localhostB服务器操作方法

        public IActionResult Message(int id = 0)
        {
            var result = string.Empty;
            var sb = new StringBuilder();
            sb.AppendFormat("retry: 10000\n\n");
            sb.AppendFormat("data: {0} {1}\n\n", "hello",id);
            Response.Headers.Add("Connection", "keep-alive");
            var a = Response.HttpContext.Connection.Id;
            return Content(sb.ToString(), "text/event-stream");
        }
localhostB客户端

 <button onclick="javascript:sendEvent()">Push Event</button> 
推送事件
localhostB js

    function contentLoaded() {
        var source = new EventSource('https://localhost:44398/home/message', {
            withCredentials: true
        });
        //var ul = $("#messages");
        source.onmessage = function (e) {

            var li = document.createElement("li");
            var returnedItem = e.data;
            li.textContent = returnedItem;
            $("#messages").append(li);
        }

        source.onerror = function (e) {
            console.log(e);
        }
    };
<script>
    var sendEvent = function () {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/home/message?id=4");
        xhr.onload = function (e) {
            console.log(e);
        }
        xhr.onerror = function (e) {
            console.log(e);
        }
        xhr.send();
    }
</script>

var sendEvent=函数(){
var xhr=new XMLHttpRequest();
xhr.open(“POST”,“/home/message?id=4”);
xhr.onload=函数(e){
控制台日志(e);
}
xhr.onerror=函数(e){
控制台日志(e);
}
xhr.send();
}