我使用以下代码在ASP.NET Web API上创建了一个服务器发送的事件:
namespace SpaServerSide.Controllers
{
public class SSEController : ApiController
{
static readonly ConcurrentQueue<StreamWriter> ConnectedClients = new ConcurrentQueue<StreamWriter>();
static System.Threading.Timer _dd = new System.Threading.Timer(OnTimerEvent, null, 0, 1000);
[Route("api/sse")]
public HttpResponseMessage Get()
{
var Response = Request.CreateResponse();
Response.Content = new PushStreamContent((Action< Stream, HttpContent, TransportContext>)OnStreamAvailabe, "text/event-stream");
return Response;
}
private static void OnStreamAvailabe(Stream stream, HttpContent headers, TransportContext context)
{
var clientStream = new StreamWriter(stream);
ConnectedClients.Enqueue(clientStream);
}
static void OnTimerEvent(object state)
{
_dd.Change(Timeout.Infinite, Timeout.Infinite);
try
{
var jsSerializer = new JavaScriptSerializer();
var message = jsSerializer.Serialize(new { msg = "Server send this response on " + DateTime.Now.ToString() });
foreach (var clientStream in ConnectedClients)
{
clientStream.WriteLine("data:" + message + Environment.NewLine + Environment.NewLine);
clientStream.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
_dd.Change(1000, 1000);
}
}
}
}
然后,我使用以下代码段使用javascript连接到此服务器:
var evtSource = new EventSource("http://localhost:5587/api/sse");
evtSource.onopen = function(e){
alert("Opened");
}
evtSource.onmessage = function(e){
console.log(e);
alert("Response Received.");
}
evtSource.onerror = function (e) {
alert('error');
};
但是,会发生异常。消息是:远程主机关闭连接。这怎么发生的?为了进一步研究,服务器发送的事件何时触发?可以手动控制吗?