服务器向Nancy发送了事件

时间:2013-06-26 13:00:28

标签: c# .net nancy server-sent-events

如何使用Nancy创建服务器发送事件。我只返回一行,但我不知道如何在我的代码中触发新事件。

这就是我在模块中所拥有的:

 Get["/events"] = _ =>
 {        
  return Response.AsText(string.Format("data: {{\"date\":{0}}}\n\n", DateTime.Now.Ticks), "text/event-stream");
 };

3 个答案:

答案 0 :(得分:2)

我可能会使用Nancy + SignalR并将其托管在OWIN上

答案 1 :(得分:1)

不需要SignalR。这可以使用NancyModule实现使用开箱即用的流完成。以下是一个例子:

public class LogModule : NancyModule
{
    public LogModule()
    {
        Get["/log"] = GetLog;
    }

    private object GetLog(object args)
    {
        return new Response
        {
            ContentType = "text/event-stream",
            Contents = stream =>
            {
                while (true)
                {
                    Thread.Sleep(1000);

                    var json = JsonConvert.SerializeObject(new Log("Test"));

                    if (!TrySendEvent(json, stream))
                        break;
                }
            }
        };
    }

    private static bool TrySendEvent(string value, Stream stream)
    {
        try
        {
            var data = Encoding.UTF8.GetBytes("data: " + value + "\n\n");
            stream.Write(data, 0, data.Length);
            stream.Flush();
            return true;
        }
        catch
        {
            return false;
        }
    }
}

答案 2 :(得分:1)

Nancy.Reaponse中,将ContentType设置为text/event-stream

public class ClockModule : NancyModule
{
    public ClockModule()
    {
        Get["/clock"] = (args) => {
            return new Response
            {
                ContentType = "text/event-stream",
                Contents = (Stream stream) =>
                {
                    var data = Encoding.UTF8.GetBytes("retry: 1000\ndata: " + DateTime.Now.ToString() + "\n\n");
                    stream.Write(data, 0, data.Length);
                    stream.Flush();
                }
            };
        };
    }
}

index.html

<html>
<body>
<div id="clock">1970-01-01</div>
<script>
new EventSource("/clock").onmessage = function(event) {
    document.getElementById("clock").innerHTML = event.data;
};
</script>
</body>
</html>

Chrome浏览器结果位于http://127.0.0.1:9487/clock

retry: 1000
data: 2018/9/28 16:40:38