服务器发送了与Nancy的事件

本文关键字:Nancy 事件 服务器 | 更新日期: 2023-09-27 18:20:08

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

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

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

服务器发送了与Nancy的事件

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

无需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;
        }
    }
}

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