我正在尝试使用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();
}
}
答案 0 :(得分:0)
答案很简单。这是Javascript。
event.onmessage = function(e) {
//Event logic
};
不应该使用。你应该使用:
event.addEventListener('message', function(e) {
//Event logic
});