服务器发送的事件连接关闭或未接收到数据

本文关键字:数据 事件 连接 服务器 | 更新日期: 2023-09-27 18:35:26

我正在尝试使用ASP.net MVC 4 web api控制器创建事件端点。问题是,当我试图刷新流时,它会抛出一个异常:

The remote host has closed the connection.

或者客户端看起来什么都没收到。即使它可以刷新写入流的数据。

我首先使用ConcurrentQueue对象将StreamWriter存储在具有标识Guid的包装器中。现在我将它作为键值对存储在ConcurrentDictionary对象中。我不知道这是否有什么不同。

客户端:

<script type="text/javascript">
    var event = new EventSource('/back-end/events/tracklisting/866594c8-8411-11e4-9fcb-5254005dbd0a?juke=392fcbe5-8523-e4-9fcb-5254005dbd0a');
    event.onopen = function () {
        console.log('Onopen event fired!');
    };
    event.onmessage = function (e) {
        console.log('incoming data: ' + e.data);
    };
    event.onerror = function () {
        console.log('Event source error occurred!');
    };
</script>

ASP.Net事件终点:

[HttpGet]
public HttpResponseMessage TrackListing(HttpRequestMessage req, string token, string juke) {
    var response = req.CreateResponse();
    response.Content = new PushStreamContent((stream, content, ctx) => {
        trackListingSubscribers.TryAdd(new Guid(juke), new StreamWriter(stream));
    }, "text/event-stream");
    response.Headers.Add("Cache-Control", "no-cache");
    return response;
}

并发流存储:

public static readonly ConcurrentDictionary<Guid, StreamWriter> trackListingSubscribers = new ConcurrentDictionary<Guid, StreamWriter>();

调度事件功能:

    public static void sendTrackListingEvent(Guid juke)
    {
        foreach(var subscriber in EventsController.trackListingSubscribers.Where(kvp => kvp.Key == juke)) {
            subscriber.Value.WriteLine(string.Format("data: {1}'"refresh'": true,'"juke_id'":'"{0}'" {2} 'n", subscriber.Key.ToString(), "{", "}"));
            subscriber.Value.Flush();
        }
    }

服务器发送的事件连接关闭或未接收到数据

答案很简单。那是Javascript。

event.onmessage = function(e) {
    //Event logic
};

不应使用。您应该使用:

event.addEventListener('message', function(e) {
    //Event logic
});