在ServiceStack中,如何从服务器广播消息?

时间:2016-07-25 14:56:30

标签: c# servicestack

是否有一个简单的教程展示了如何将服务器事件与ServiceStack一起使用?具体来说,我正在寻找让服务器生成要向所有客户广播的消息的方法。

我一直在阅读ServiceStack documentation并使用示例Chat应用程序,但这两个来源都没有提供足够的信息。文档存在差距,聊天应用程序膨胀,仅显示如何发送客户端而不是服务器触发的消息,我无法弄清楚如何调整该代码。

1 个答案:

答案 0 :(得分:2)

Server Events Docs显示可用于发布服务器事件的不同API:

public interface IServerEvents : IDisposable
{
    // External API's
    void NotifyAll(string selector, object message);
    void NotifyChannel(string channel, string selector, object message);
    void NotifySubscription(string subscriptionId, string selector, object message, string channel = null);
    void NotifyUserId(string userId, string selector, object message, string channel = null);
    void NotifyUserName(string userName, string selector, object message, string channel = null);
    void NotifySession(string sspid, string selector, object message, string channel = null);
    //..
}

因此,您可以使用NotifyAll API向所有订阅者发送消息,例如:

public class MyServices : Service
{
    public IServerEvents ServerEvents { get; set; }

    public object Any(Request request)
    {
        ServerEvents.NotifyAll("cmd.mybroadcast", request);
        ...
    }
}

由于它使用的是cmd.*选择器,因此可以handled in JavaScript clients使用:

$(source).handleServerEvents({
    handlers: {
        mybroadcast: function(msg,e) { ... }
    }
});

但是,您很少想要向所有订阅者发送消息,而不仅仅是通道中的订阅者。

服务器事件示例

ServiceStack参考聊天应用中的所有JavaScript服务器事件处理程序均为captured in 40 lines of JavaScript且仅2 ServiceStack Services on the Server,并展示了JavaScript Server Events中的大部分功能。

如果聊天应用程序不清楚,请查看其他Server Event Examples,例如Real-time Networked Time Traveller通过并解释了它如何使用服务器事件来远程控制正在观看用户应用程序的所有应用程序。