Web API服务器已发送事件无法正常工作

时间:2014-11-30 17:19:54

标签: javascript c# asp.net-web-api server-sent-events

我目前正在开发一个网站,该网站也应该包含推送通知。我想使用服务器发送的事件,因为我不需要将我的事件的答案从客户端发送回服务器,因此不需要websockets

后端是C#Web Api服务,代码基于此tutorial

public async Task<HttpResponseMessage> Get(HttpRequestMessage request)
{
    HttpResponseMessage response = request.CreateResponse();
    Action<Stream, HttpContent, TransportContext> onStreamAvailable = delegate(Stream stream, HttpContent headers, TransportContext context)
    {
        if (stream != null)
        {
            StreamWriter outStream = new StreamWriter(stream);

            outStream.WriteLine("event: testEvent");
            outStream.WriteLine("data: hello world1!");
            outStream.WriteLine("");
            outStream.Flush();

            outStream.WriteLine("event: testEvent");
            outStream.WriteLine("data: hello world Nr. 2!");
            outStream.WriteLine("");
            outStream.Flush();

            outStream.WriteLine("event: testEvent");
            outStream.WriteLine("data: hello world Nr. 3!");
            outStream.WriteLine("");
            outStream.Flush();

            outStream.WriteLine("event: testEvent");
            outStream.WriteLine("data: hello world Nr. 4!");
            outStream.WriteLine("");
            outStream.Flush();

            outStream.WriteLine("event: testEvent");
            outStream.WriteLine("data: hello world Nr. 5!");
            outStream.WriteLine("");
            outStream.Flush();

        }

    };


    response.Content = new PushStreamContent(onStreamAvailable, "text/event-stream");
    return response;
}

使用此代码时,浏览器显示前四条消息,但不显示最后一条消息。然后我启动了调试模式,发现浏览器显示第一个事件,就在第二个事件被刷新之后,等等。

然后我发出一个telnet请求来查看输出,结果就是这样:

telnet result

这里我注意到在每个事件之前似乎都有一些文本(可能是一个十六进制的字节),我没有发送。我想也许这就是浏览器遇到的问题。

知道我可以做些什么来删除它?或者错误是什么?

以下是浏览器的JavaScript代码:

<script type="text/javascript">
    $(document).ready(function() {
        var serverSentEvents = new window.EventSource('http://localhost:1278/api/subscribe');
        serverSentEvents.onmessage = function (e) {
            $("#messages").append(e.data + '<br />');
        };

        serverSentEvents.addEventListener("testEvent", function (e) {
            $("#messages").append(e.data + '<br />');
        });

        serverSentEvents.onerror = function (e) {
            alert('error');
        };
    });
</script>

0 个答案:

没有答案