[SignalR Learning Series] 7. SignalR Hubs Api details (JavaScript client), signalrhubs
Generated proxy server of SignalR
public class ContosoChatHub : Hub{ public void NewContosoChatMessage(string name, string message) { Clients.All.addContosoChatMessageToPage(name, message); }}
JavaScript Client
Generated proxy
var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) { console.log(name + ' ' + message);};$.connection.hub.start().done(function () { // Wire up Send button to call NewContosoChatMessage on the server. $('#newContosoChatMessage').click(function () { contosoChatHubProxy.server.newContosoChatMessage($('#displayname').val(), $('#message').val()); $('#message').val('').focus(); });});
Non-generated proxy
var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');contosoChatHubProxy.on('addContosoChatMessageToPage', function(name, message) { console.log(name + ' ' + message);});connection.start().done(function() { // Wire up Send button to call NewContosoChatMessage on the server. $('#newContosoChatMessage').click(function () { contosoChatHubProxy.invoke('newContosoChatMessage', $('#displayname').val(), $('#message').val()); $('#message').val('').focus(); }); })
When to use generated proxy
If you want to register multiple event processors for the client method, you cannot use generated proxy. If you do not use generated proxy, you cannot reference the "signalr/hubs" URL.
The client must first reference jQuery, SignalR, signalr/hubs
<script src="Scripts/jquery-1.10.2.min.js"></script><script src="Scripts/jquery.signalR-2.1.0.min.js"></script><script src="signalr/hubs"></script>
How to reference dynamic generated proxy
ASP. net mvc 4 or 5 Razor
<script src="~/signalr/hubs"></script>
ASP. net mvc 3 Razor
<script src="@Url.Content("~/signalr/hubs")"></script>
ASP. NET Web Forms
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>
/Signalr/hubs is automatically generated by SignalR. When you start debugging, you will see it in Script Documents.
Create a connection
Create a connection (generated proxy)
var contosoChatHubProxy = $.connection.contosoChatHub;contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) { console.log(userName + ' ' + message);};$.connection.hub.start() .done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); }) .fail(function(){ console.log('Could not Connect!'); });
Establish a connection (non-generated proxy Mode)
var connection = $.hubConnection();var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');contosoChatHubProxy.on('addContosoChatMessageToPage', function(userName, message) { console.log(userName + ' ' + message);});connection.start() .done(function(){ console.log('Now connected, connection ID=' + connection.id); }) .fail(function(){ console.log('Could not connect'); });
$. Connection. hub and $. hubConnection () create the same object.
Asynchronous execution of the start Method
The start method is executed asynchronously. It returns a jQuery Deferred object. You can add a callback function to pipe, done, and fail.
When you directly put the "Now connected" code behind the start method, rather than in the callback function of. done, the console. log will be executed before the connection.
How to enable cross-origin connection
First install Microsoft. Owin. Cors, and then use Map and RunSignalR to replace MapSignalR. The cross-origin middleware will only execute in the SignalR request that requires cross-origin.
using Microsoft.AspNet.SignalR;using Microsoft.Owin.Cors;using Owin;namespace MyWebApplication{ public class Startup { public void Configuration(IAppBuilder app) { // Branch the pipeline here for requests that start with "/signalr" app.Map("/signalr", map => { // Setup the CORS middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { // You can enable JSONP by uncommenting line below. // JSONP requests are insecure but some older browsers (and some // versions of IE) require JSONP to work cross domain // EnableJSONP = true }; // Run the SignalR pipeline. We're not using MapSignalR // since this branch already runs under the "/signalr" // path. map.RunSignalR(hubConfiguration); }); } }}
How to handle connection lifecycle events
SignalR provides the following lifecycle events that you can capture.
- Starting: Execute before any data is sent.
- Received: executed when any data is obtained through a connection. You can get the data.
- ConnectionSlow: it is executed when the client detects a slow or influshed connection.
- Reconnecting: executed when the potential protocol restarts the connection.
- Reconnected: executed when potential protocols and connections are established again.
- StateChanged: it is executed when the connection status changes. It can provide an old and new status (Connecting, Connected, Reconnecting, or Disconnected ).
- Disconnected: executed after the connection is interrupted.
Capture connectionSlow events (generated proxy Mode)
$.connection.hub.connectionSlow(function () { console.log('We are currently experiencing difficulties with the connection.')});
Capture connectionSlow events (non-generated proxy Mode)
var connection = $.hubConnection();connection.connectionSlow(function () { console.log('We are currently experiencing difficulties with the connection.')});
How to capture and handle exceptions
If you do not explicitly open the detailed error information on the server, SignalR will only list some simple error information. You can enable the detailed error information record through the following code.
var hubConfiguration = new HubConfiguration();hubConfiguration.EnableDetailedErrors = true;app.MapSignalR(hubConfiguration);
Add a capture method to an error event
Generated proxy method
$.connection.hub.error(function (error) { console.log('SignalR error: ' + error)});
Non-generated proxy method
var connection = $.hubConnection();connection.error(function (error) { console.log('SignalR error: ' + error)});
Capture exceptions when calling methods
Generated proxy method
contosoChatHubProxy.newContosoChatMessage(userName, message) .fail(function(error) { console.log( 'newContosoChatMessage error: ' + error) });
Non-generated proxy method
contosoChatHubProxy.invoke('newContosoChatMessage', userName, message) .fail(function(error) { console.log( 'newContosoChatMessage error: ' + error) });
Enable client Logging
Generated proxy method
$.connection.hub.logging = true;$.connection.hub.start();
Non-generated proxy method
var connection = $.hubConnection();connection.logging = true;connection.start();
Reference link:
Https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client