SignalR: Why choose Hub vs. Persistent Connection?

后端 未结 5 853
一个人的身影
一个人的身影 2020-12-04 09:20

I\'ve been searching and reading up on SignalR recently and, while I see a lot of explanation of what the difference is between Hubs and Persistent Connections I haven\'t be

5条回答
  •  心在旅途
    2020-12-04 09:53

    The main difference is that you can't do RPC with PersistentConnection, you can only send raw data. So instead of sending messages from the server like this

    Clients.All.addNewMessageToPage(name, message);
    

    you'd have to send an object with Connection.Broadcast() or Connection.Send() and then the client would have to decide what to do with that. You could, for example, send an object like this:

    Connection.Broadcast(new {
        method: "addNewMessageToPage",
        name: "Albert",
        message: "Hello"
    });
    

    And on the client, instead of simply defining

    yourHub.client.addNewMessageToPage = function(name, message) { 
        // things and stuff
    };
    

    you'd have to add a callback to handle all incoming messages:

    function addNewMessageToPage(name, message) {
        // things and stuff
    }
    
    connection.received(function (data) {
        var method = data.method;
    
        window[method](data.name, data.message);
    });
    

    You'd have to do the same kind of dispatching on the server side in the OnReceived method. You'd also have to deserialize the data string there instead of receiving the strongly typed objects as you do with hub methods.

    There aren't many reasons to choose PersistentConnection over Hubs. One reason I'm aware of is that it is possible to send preserialized JSON via PersistentConnection, which you can't do using hubs. In certain situations, this might be a relevant performance benefit.

    Apart from that, see this quote from the documentation:

    Choosing a communication model

    Most applications should use the Hubs API. The Connections API could be used in the following circumstances:

    • The format of the actual message sent needs to be specified.

    • The developer prefers to work with a messaging and dispatching model rather than a remote invocation model.

    • An existing application that uses a messaging model is being ported to use SignalR.

    Depending on your message structure, you might also get small perfomance benefits from using PersistentConnection.

    You may want to take a look at the SignalR samples, specifically this here.

提交回复
热议问题