When a connection is made, a transport strategy must be put in place in order to properly move bits back and forth between the client and the server. SignalR can choose among different transport options as follows:
Each one of these strategies is based on a specific underlying technology, which may or may not be available according to the specific browser used and to the capabilities of the web server in place. SignalR will try to use WebSocket whenever possible, and if it's not available, it will gracefully fall back on the remaining ones until it picks the best option for the current environment. That said, we might have good reasons to decide on a specific one or to define a custom probing sequence. In this recipe, we'll see how to do this.
For some more details about the transport options, please have a look at Appendix B, Insights.
As for the previous recipe, this one does not need a server-side concrete Hub yet. We just need to perform the following steps:
Configuration()
method calls app.MapSignalR();
in order to properly initiate the server-side endpoint. This method is contained in the Microsoft ASP.NET SignalR System.Web package, which we can find on NuGet.For more details about these steps, you can check the previous recipe.
Let's proceed with the client code by performing the following steps:
<script src="Scripts/jquery-2.1.0.js"></script> <script src="Scripts/jquery.signalR-2.0.2.js"></script> <script src="/signalr/hubs"></script>
<script> var hub = $.connection.hub; var started = hub.start({ transport: [ 'webSockets', 'longPolling', 'serverSentEvents', 'foreverFrame' ] }); started.done(function () { $('#connected') .html('connected, transport: ' + hub.transport.name); }); </script>
The preceding code is very similar to the code in the previous recipe, but the start()
method is given a transport
option that lists a specific sequence of connection strategies, which will be used by SignalR to pick the best one available. We can change the order, remove any of these, or even specify just one, in which case we can pass a simple string instead of an array of strings. When the connection is ready, we can get the current transport strategy by querying the hub.transport.name
value. If we tried to print this value just after the start call, we would get an undefined value because the transport is available only when the connection is asynchronously established.
Not every strategy may be available to a specific combination of the server and client technologies. A specific description of all the cases is outside the scope of this book, and it would become obsolete quite quickly. For the current list of specific cases, you can visit http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/supported-platforms. However, you might have to periodically check the list or look for a more up-to-date one in the future.