我有一个RESTful Web API 2解决方案,其方法是从AngularJS应用程序调用的。我想添加对从服务器端API向客户端逻辑发送通知的支持。但是,永远不会调用通过调用Javascript中的addEventListener来设置消息和打开方法。 Web API控制器如下:
namespace Controllers
{
public class EventController : ApiController
{
private static readonly List<StreamWriter> ConnectedClients = new List<StreamWriter>();
private static Timer _timer;
public EventController()
{
if(_timer == null)
_timer = new Timer(TimerCallback, null, 0, 2000);
}
public static void OnStreamAvailable(Stream stream, HttpContent headers, TransportContext context)
{
var streamwriter = new StreamWriter(stream);
ConnectedClients.Add(streamwriter);
}
private static void MessageCallback(Message m)
{
foreach (var subscriber in ConnectedClients)
{
try
{
subscriber.Write("data: {0}\n\n", JsonConvert.SerializeObject(m));
subscriber.Flush();
}
catch (Exception ex)
{
// This probably means the user has disconnected
ConnectedClients.Remove(subscriber);
}
}
}
private static void TimerCallback(object state)
{
var m = new Message
{
Date = DateTime.Now.ToUniversalTime().ToString("u"),
Text = "Hello World!"
};
MessageCallback(m);
}
[HttpGet]
public HttpResponseMessage Get(HttpRequestMessage request)
{
// New subscription request
var response = request.CreateResponse();
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Cache-Control", "no-cache, must-revalidate");
response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)OnStreamAvailable, "text/event-stream");
return response;
}
}
}
请注意,我还尝试了以下HttpGet方法:
public HttpResponseMessage Get()
{
// New subscription request
var response = Request.CreateResponse();
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Cache-Control", "no-cache, must-revalidate");
response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)OnStreamAvailable, "text/event-stream");
return response;
}
Javascript:
if (!!window.EventSource) {
var eventSource = new EventSource(GlobalConfig.apiRoot + 'Event');
eventSource.addEventListener('open', function (e) {
console.log("open");
}, false);
eventSource.addEventListener('error', function (e) {
console.log("error");
}, false);
eventSource.addEventListener('message', function (e) {
console.log('message');
}, false);
} else {
// not supported!
}
我在Visual Studio 2013下通过IISExpress运行。但是我也在IIS 8下测试了相同的结果。所有测试均在Google Chrome 36.0.1985.143 m版本中完成。我可以验证的是:
也就是说,似乎确实存在某种连接,但我无法弄清楚为什么永远不会在Javascript中调用消息和打开处理程序。
要检查AngularJS中是否有任何内容影响了我将Javascript移动到静态HTML页面。 Chrome控制台中记录了以下内容:
Request URL:http://localhost/.../api/Event
Request Headers
Provisional headers are shown
Accept:text/event-stream
Cache-Control:no-cache
Referer:http://localhost/.../test.html
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
请求的状态始终为“待处理”。然而,鉴于连接保持打开,这是我所期望的。
任何有关获得此功能的建议都将非常感激。
答案 0 :(得分:0)
我认为正确的格式是:
subscriber.Write("event: message\n");
subscriber.Write("data: {0}\n\n");
事件侦听器仅响应包含事件消息名称的事件(在本例中为message
)。这意味着服务器能够发送可以单独订阅的多种事件类型。