简体   繁体   中英

In ServiceStack, how do I broadcast messages from the Server?

Is there a simple tutorial showing how to use Server Events with ServiceStack? Specifically, I'm looking for a way to have a server generate messages to be broadcast to all clients.

I've been reading the ServiceStack documentation and playing with the sample Chat application but neither source is very informative. The documentation has gaps and the chat application is bloated and only shows how to send messages triggered by the client, not by the server and I can't figure out how to adapt that code.

The Server Events Docs shows the different APIs available for publishing Server Events:

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);
    //..
}

So you can use the NotifyAll API to send a message to all subscribers, eg:

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

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

Which since it's using a cmd.* selector, it can be handled in JavaScript clients with:

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

However it should be rare that you want to send a message to all Subscribers instead of just the Subscribers in your channel.

Server Event Examples

All JavaScript Server Event handlers in ServiceStack's reference Chat App is captured in 40 lines of JavaScript and only 2 ServiceStack Services on the Server and showcases most of the features in JavaScript Server Events .

If the Chat App isn't clear have a look at the other Server Event Examples , eg the Real-time Networked Time Traveller goes through and explains how it uses Server Events to remote control all apps that are watching the Users App.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM