2

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

这就是我在我的模块中所做的:

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

3 回答 3

2

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

于 2013-06-26T19:57:53.543 回答
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;
        }
    }
}
于 2018-06-02T15:57:57.103 回答
1

Nancy.Reaponse,设置ContentTypetext/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();
                }
            };
        };
    }
}

索引.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
于 2018-09-28T03:33:14.330 回答