SignalR Hubs API Guide - Server (C#) - The ASP
SignalR Hubs API Guide - Server (C#) - The ASP
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
This document provides an introduction to programming the server side of the ASP.NET SignalR Hubs API for
SignalR version 2, with code samples demonstrating common options.
The SignalR Hubs API enables you to make remote procedure calls RPCs from a server to connected clients
and from clients to the server. In server code, you define methods that can be called by clients, and you call
methods that run on the client. In client code, you define methods that can be called from the server, and you
call methods that run on the server. SignalR takes care of all of the clienttoserver plumbing for you.
SignalR also offers a lowerlevel API called Persistent Connections. For an introduction to SignalR, Hubs, and
Persistent Connections, see Introduction to SignalR 2 /signalr/overview/signalr20/gettingstartedwith
signalr20/introductiontosignalr .
1/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
2/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
}
}
If you are adding SignalR functionality to an ASP.NET MVC application, make sure that the SignalR route is added
before the other routes. For more information, see Tutorial: Getting Started with SignalR 2 and MVC 5
/signalr/overview/signalr20/gettingstartedwithsignalr20/tutorialgettingstartedwithsignalr20andmvc5 .
JavaScript client code that specifies the URL with the generated proxy
$.connection.hub.url="/signalr"
$.connection.hub.start().done(init);
JavaScript client code that specifies the URL without the generated proxy
varconnection=$.hubConnection("/signalr",{useDefaultPath:false});
3/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
In this example, a connected client can call the NewContosoChatMessage method, and when it does, the data
received is broadcasted to all connected clients.
4/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
You don't instantiate the Hub class or call its methods from your own code on the server; all that is done for you by
the SignalR Hubs pipeline. SignalR creates a new instance of your Hub class each time it needs to handle a Hub
operation such as when a client connects, disconnects, or makes a method call to the server.
Because instances of the Hub class are transient, you can't use them to maintain state from one method call to the
next. Each time the server receives a method call from a client, a new instance of your Hub class processes the
message. To maintain state through multiple connections and method calls, use some other method such as a
database, or a static variable on the Hub class, or a different class that does not derive from Hub. If you persist data in
memory, using a method such as a static variable on the Hub class, the data will be lost when the app domain
recycles.
If you want to send messages to clients from your own code that runs outside the Hub class, you can't do it by
instantiating a Hub class instance, but you can do it by getting a reference to the SignalR context object for your Hub
class. For more information, see How to call client methods and manage groups from outside the Hub class
#callfromoutsidehub later in this topic.
If you want to specify a different name for clients to use, add the HubName attribute. When you use a HubName
attribute, there is no name change to camel case on JavaScript clients.
Server
[HubName("PascalCaseContosoChatHub")]
publicclassContosoChatHub:Hub
Multiple Hubs
You can define multiple Hub classes in an application. When you do that, the connection is shared but groups are
separate:
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
5/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
All clients will use the same URL to establish a SignalR connection with your service "/signalr" or your custom
URL if you specified one, and that connection is used for all Hubs defined by the service.
There is no performance difference for multiple Hubs compared to defining all Hub functionality in a single
class.
All Hubs get the same HTTP request information.
Since all Hubs share the same connection, the only HTTP request information that the server gets is what comes
in the original HTTP request that establishes the SignalR connection. If you use the connection request to pass
information from the client to the server by specifying a query string, you can't provide different query strings to
different Hubs. All Hubs will receive the same information.
The generated JavaScript proxies file will contain proxies for all Hubs in one file.
For information about JavaScript proxies, see SignalR Hubs API Guide JavaScript Client The generated
proxy and what it does for you /signalr/overview/signalr20/hubsapi/hubsapiguidejavascript
client#genproxy .
Groups are defined within Hubs.
In SignalR you can define named groups to broadcast to subsets of connected clients. Groups are maintained
separately for each Hub. For example, a group named "Administrators" would include one set of clients for your
ContosoChatHub class, and the same group name would refer to a different set of clients for your
StockTickerHub class.
StronglyTyped Hubs
To define an interface for your hub methods that your client can reference and enable Intellisense on your hub
methods, derive your hub from Hub<T> introduced in SignalR 2.1 rather than Hub:
publicclassStrongHub:Hub<IClient>
{
publicvoidSend(stringmessage)
{
Clients.All.NewMessage(message);
}
}
publicinterfaceIClient
{
voidNewMessage(stringmessage);
}
How to define methods in the Hub class that clients can call
To expose a method on the Hub that you want to be callable from the client, declare a public method, as shown in
the following examples.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
6/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
publicclassContosoChatHub:Hub
{
publicvoidNewContosoChatMessage(stringname,stringmessage)
{
Clients.All.addNewMessageToPage(name,message);
}
}
publicclassStockTickerHub:Hub
{
publicIEnumerable<Stock>GetAllStocks()
{
return_stockTicker.GetAllStocks();
}
}
You can specify a return type and parameters, including complex types and arrays, as you would in any C# method.
Any data that you receive in parameters or return to the caller is communicated between the client and the server by
using JSON, and SignalR handles the binding of complex objects and arrays of objects automatically.
If you want to specify a different name for clients to use, add the HubMethodName attribute.
Server
[HubMethodName("PascalCaseNewContosoChatMessage")]
publicvoidNewContosoChatMessage(stringuserName,stringmessage)
7/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
Asynchronous
publicasyncTask<IEnumerable<Stock>>GetAllStocks()
{
//Returnsdatafromawebservice.
varuri=Util.getServiceUri("Stocks");
using(HttpClienthttpClient=newHttpClient())
{
varresponse=awaithttpClient.GetAsync(uri);
return(awaitresponse.Content.ReadAsAsync<IEnumerable<Stock>>());
}
}
For more information about how to use asynchronous methods in ASP.NET 4.5, see Using Asynchronous Methods
in ASP.NET MVC 4 /mvc/tutorials/mvc4/usingasynchronousmethodsinaspnetmvc4 .
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
8/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
Defining Overloads
If you want to define overloads for a method, the number of parameters in each overload must be different. If you
differentiate an overload just by specifying different parameter types, your Hub class will compile but the SignalR
service will throw an exception at run time when clients try to call one of the overloads.
When writing a longrunning server method, it is important to use an asynchronous programming pattern like Async/
Await rather than blocking the hub thread.
9/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
//Addthemessagetothepage.
$('#discussion').append('<li><strong>'+htmlEncode(name)
+'</strong>:'+htmlEncode(message)+'<li>');
};
You can't get a return value from a client method; syntax such as intx=Clients.All.add(1,1) does not work.
You can specify complex types and arrays for the parameters. The following example passes a complex type to the
client in a method parameter.
Server code that calls a client method using a complex object
publicvoidSendMessage(stringname,stringmessage)
{
Clients.All.addContosoChatMessageToPage(newContosoChatMessage(){UserName=name,
Message=message});
}
.addContosoChatMessageToPage(name,message);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
10/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
.addContosoChatMessageToPage(name,message);
.addContosoChatMessageToPage(name,message);
(Context.ConnectionId).addContosoChatMessageToPage(name,message);
This example calls addContosoChatMessageToPage on the calling client and has the same effect as using
Clients.Caller.
All connected clients except the specified clients, identified by connection ID.
Clients.AllExcept(http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.allexcept(v=vs.111).aspx)
(connectionId1,connectionId2).addContosoChatMessageToPage(name,message);
(groupName).addContosoChatMessageToPage(name,message);
All connected clients in a specified group except the specified clients, identified by connection ID.
Clients.Group(http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.group(v=vs.111).aspx)(groupName,
connectionId1,connectionId2).addContosoChatMessageToPage(name,message);
11/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.othersingroup(v=vs.111).aspx)
(groupName).addContosoChatMessageToPage(name,message);
A list of groups.
Clients.Groups(GroupIds).broadcastMessage(name,message);
A user by name.
Clients.Client(username).broadcastMessage(name,message);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
12/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
Asynchronous execution
The method that you call executes asynchronously. Any code that comes after a method call to a client will execute
immediately without waiting for SignalR to finish transmitting data to clients unless you specify that the subsequent
lines of code should wait for method completion. The following code example shows how to execute two client
methods sequentially.
Using Await .NET 4.5
publicasyncTaskNewContosoChatMessage(stringname,stringmessage)
{
awaitClients.Others.addContosoChatMessageToPage(data);
Clients.Caller.notifyMessageSent();
}
If you use await to wait until a client method finishes before the next line of code executes, that does not mean that
clients will actually receive the message before the next line of code executes. "Completion" of a client method call
only means that SignalR has done everything necessary to send the message. If you need verification that clients
received the message, you have to program that mechanism yourself. For example, you could code a
MessageReceived method on the Hub, and in the addContosoChatMessageToPage method on the client you could
call MessageReceived after you do whatever work you need to do on the client. In MessageReceived in the Hub you
can do whatever work depends on actual client reception and processing of the original method call.
13/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
publicclassContosoChatHub:Hub
{
publicTaskJoinGroup(stringgroupName)
{
returnGroups.Add(Context.ConnectionId,groupName);
}
publicTaskLeaveGroup(stringgroupName)
{
returnGroups.Remove(Context.ConnectionId,groupName);
}
}
contosoChatHubProxy.server.leaveGroup(groupName);
You don't have to explicitly create groups. In effect a group is automatically created the first time you specify its
name in a call to Groups.Add, and it is deleted when you remove the last connection from membership in it.
There is no API for getting a group membership list or a list of groups. SignalR sends messages to clients and groups
based on a pub/sub model http://en.wikipedia.org/wiki/Publish/subscribe , and the server does not maintain lists of
groups or group memberships. This helps maximize scalability, because whenever you add a node to a web farm, any
state that SignalR maintains has to be propagated to the new node.
14/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
After a temporary loss of connectivity, sometimes SignalR can restore the connection automatically. In that case,
SignalR is restoring the same connection, not establishing a new connection, and so the client's group membership is
automatically restored. This is possible even when the temporary break is the result of a server reboot or failure,
because connection state for each client, including group memberships, is roundtripped to the client. If a server goes
down and is replaced by a new server before the connection times out, a client can reconnect automatically to the
new server and reenroll in groups it is a member of.
When a connection can't be restored automatically after a loss of connectivity, or when the connection times out, or
when the client disconnects for example, when a browser navigates to a new page, group memberships are lost. The
next time the user connects will be a new connection. To maintain group memberships when the same user
establishes a new connection, your application has to track the associations between users and groups, and restore
group memberships each time a user establishes a new connection.
For more information about connections and reconnections, see How to handle connection lifetime events in the
Hub class #connectionlifetime later in this topic.
Singleuser groups
Applications that use SignalR typically have to keep track of the associations between users and connections in order
to know which user has sent a message and which users should be receiving a message. Groups are used in one of
the two commonly used patterns for doing that.
Singleuser groups.
You can specify the user name as the group name, and add the current connection ID to the group every time
the user connects or reconnects. To send messages to the user you send to the group. A disadvantage of this
method is that the group doesn't provide you with a way to find out if the user is online or offline.
Track associations between user names and connection IDs.
You can store an association between each user name and one or more connection IDs in a dictionary or
database, and update the stored data each time the user connects or disconnects. To send messages to the user
you specify the connection IDs. A disadvantage of this method is that it takes more memory.
15/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
returnbase.OnConnected();
}
publicoverrideTaskOnDisconnected()
{
//Addyourowncodehere.
//Forexample:inachatapplication,marktheuserasoffline,
//deletetheassociationbetweenthecurrentconnectionidandusername.
returnbase.OnDisconnected();
}
publicoverrideTaskOnReconnected()
{
//Addyourowncodehere.
//Forexample:inachatapplication,youmighthavemarkedthe
//userasofflineafteraperiodofinactivity;inthatcase
//marktheuserasonlineagain.
returnbase.OnReconnected();
}
}
How to get information about the client from the Context property
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
16/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
To get information about the client, use the Context property of the Hub class. The Context property returns a
HubCallerContext http://msdn.microsoft.com/enus/library/jj890883v=vs.111.aspx object which provides access to
the following information:
The connection ID of the calling client.
stringconnectionID=Context.ConnectionId;
The connection ID is a GUID that is assigned by SignalR you can't specify the value in your own code. There is
one connection ID for each connection, and the same connection ID is used by all Hubs if you have multiple
Hubs in your application.
HTTP header data.
System.Collections.Specialized.NameValueCollectionheaders=Context.Request.Headers;
You can also get HTTP headers from Context.Headers. The reason for multiple references to the same thing is
that Context.Headers was created first, the Context.Request property was added later, and
Context.Headers was retained for backward compatibility.
Query string data.
System.Collections.Specialized.NameValueCollectionqueryString=
Context.Request.QueryString;
stringparameterValue=queryString["parametername"]
For more information about setting query string parameters, see the API guides for the JavaScript
/signalr/overview/signalr20/hubsapi/hubsapiguidejavascriptclient and .NET /signalr/overview/signalr
20/hubsapi/hubsapiguidenetclient clients.
You can find the transport method used for the connection in the query string data, along with some other
values used internally by SignalR:
stringtransportMethod=queryString["transport"];
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
17/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
Use this method instead of getting HttpContext.Current to get the HttpContext object for the SignalR
connection.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
18/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
In your Hub class, you can access this data in the Clients.Caller property. The following example shows code that
retrieves the state referred to in the previous example.
publicvoidNewContosoChatMessage(stringdata)
{
stringuserName=Clients.Caller.userName;
stringcomputerName=Clients.Caller.computerName;
Clients.Others.addContosoChatMessageToPage(message,userName,computerName);
}
Note: This mechanism for persisting state is not intended for large amounts of data, since
everything you put in the state or Clients.Caller property is roundtripped with every
method invocation. It's useful for smaller items such as user names or counters.
In VB.NET or in a stronglytyped hub, the caller state object can't be accessed through Clients.Caller; instead, use
Clients.CallerState introduced in SignalR 2.1:
Using CallerState in C#
publicvoidNewContosoChatMessage(stringdata)
{
stringuserName=Clients.CallerState.userName;
stringcomputerName=Clients.CallerState.computerName;
Clients.Others.addContosoChatMessageToPage(data,userName,computerName);
}
19/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
following example shows a pipeline module that logs errors, followed by code in Startup.cs that injects the
module into the Hubs pipeline.
publicclassErrorHandlingPipelineModule:HubPipelineModule
{
protectedoverridevoidOnIncomingError(ExceptionContextexceptionContext,
IHubIncomingInvokerContextinvokerContext)
{
Debug.WriteLine("=>Exception"+exceptionContext.Error.Message);
if(exceptionContext.Error.InnerException!=null)
{
Debug.WriteLine("=>InnerException"+
exceptionContext.Error.InnerException.Message);
}
base.OnIncomingError(exceptionContext,invokerContext);
}
}
publicvoidConfiguration(IAppBuilderapp)
{
//Anyconnectionorhubwireupandconfigurationshouldgohere
GlobalHost.HubPipeline.AddModule(newErrorHandlingPipelineModule());
app.MapSignalR();
}
Use the HubException class introduced in SignalR 2. This error can be thrown from any hub invocation. The
HubError constructor takes a string message, and an object for storing extra error data. SignalR will auto
serialize the exception and send it to the client, where it will be used to reject or fail the hub method invocation.
The following code samples demonstrate how to throw a HubException during a Hub invocation, and how to
handle the exception on JavaScript and .NET clients.
Server code demonstrating the HubException class
publicclassMyHub:Hub
{
publicvoidSend(stringmessage)
{
if(message.Contains("<script>"))
{
thrownewHubException("Thismessagewillflowtotheclient",new{user=
Context.User.Identity.Name,message=message});
}
Clients.All.send(message);
}
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
20/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
For more information about Hub pipeline modules, see How to customize the Hubs pipeline #hubpipeline later in
this topic.
21/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
<httpRuntimetargetFramework="4.5"/>
</system.web>
<system.webServer>
<modulesrunAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.diagnostics>
<sources>
<sourcename="SignalR.SqlMessageBus">
<listeners>
<addname="SignalRBus"/>
</listeners>
</source>
<sourcename="SignalR.ServiceBusMessageBus">
<listeners>
<addname="SignalRBus"/>
</listeners>
</source>
<sourcename="SignalR.ScaleoutMessageBus">
<listeners>
<addname="SignalRBus"/>
</listeners>
</source>
<sourcename="SignalR.Transports.WebSocketTransport">
<listeners>
<addname="SignalRTransports"/>
</listeners>
</source>
<sourcename="SignalR.Transports.ServerSentEventsTransport">
<listeners>
<addname="SignalRTransports"/>
</listeners>
</source>
<sourcename="SignalR.Transports.ForeverFrameTransport">
<listeners>
<addname="SignalRTransports"/>
</listeners>
</source>
<sourcename="SignalR.Transports.LongPollingTransport">
<listeners>
<addname="SignalRTransports"/>
</listeners>
</source>
<sourcename="SignalR.Transports.TransportHeartBeat">
<listeners>
<addname="SignalRTransports"/>
</listeners>
</source>
</sources>
<switches>
<addname="SignalRSwitch"value="Verbose"/>
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
22/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
</switches>
<sharedListeners>
<addname="SignalRTransports"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="transports.log.txt"/>
<addname="SignalRBus"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="bus.log.txt"/>
</sharedListeners>
<traceautoflush="true"/>
</system.diagnostics>
<entityFramework>
<defaultConnectionFactory
type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory,EntityFramework">
<parameters>
<parametervalue="v11.0"/>
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
When you run the application in Visual Studio, you can view the logs in the Output window.
How to call client methods and manage groups from outside the Hub class
To call client methods from a different class than your Hub class, get a reference to the SignalR context object for the
Hub and use that to call methods on the client or manage groups.
The following sample StockTicker class gets the context object, stores it in an instance of the class, stores the class
instance in a static property, and uses the context from the singleton class instance to call the updateStockPrice
method on clients that are connected to a Hub named StockTickerHub.
//Forthecompleteexample,goto
//http://www.asp.net/signalr/overview/gettingstarted/tutorialserverbroadcastwith
aspnetsignalr
//ThissampleonlyshowscoderelatedtogettingandusingtheSignalRcontext.
publicclassStockTicker
{
//Singletoninstance
privatereadonlystaticLazy<StockTicker>_instance=newLazy<StockTicker>(
()=>newStockTicker(GlobalHost.ConnectionManager.GetHubContext<StockTickerHub>
()));
privateIHubContext_context;
privateStockTicker(IHubContextcontext)
{
_context=context;
}
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
23/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
//ThismethodisinvokedbyaTimerobject.
privatevoidUpdateStockPrices(objectstate)
{
foreach(varstockin_stocks.Values)
{
if(TryUpdateStockPrice(stock))
{
_context.Clients.All.updateStockPrice(stock);
}
}
}
If you need to use the context multipletimes in a longlived object, get the reference once and save it rather than
getting it again each time. Getting the context once ensures that SignalR sends messages to clients in the same
sequence in which your Hub methods make client method invocations. For a tutorial that shows how to use the
SignalR context for a Hub, see Server Broadcast with ASP.NET SignalR /signalr/overview/signalr20/gettingstarted
withsignalr20/tutorialserverbroadcastwithsignalr20 .
.addContosoChatMessageToPage(name,message);
(connectionID).addContosoChatMessageToPage(name,message);
All connected clients except the specified clients, identified by connection ID.
context.Clients.AllExcept(http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.allexcept(v=vs.111).aspx)
(connectionId1,connectionId2).addContosoChatMessageToPage(name,message);
24/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
context.Clients.Group(http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.group(v=vs.111).aspx)
(groupName).addContosoChatMessageToPage(name,message);
All connected clients in a specified group except specified clients, identified by connection ID.
Clients.Group(http://msdn.microsoft.com/en
us/library/microsoft.aspnet.signalr.hubs.hubconnectioncontext.group(v=vs.111).aspx)(groupName,
connectionId1,connectionId2).addContosoChatMessageToPage(name,message);
If you are calling into your nonHub class from methods in your Hub class, you can pass in the current connection ID
and use that with Clients.Client, Clients.AllExcept, or Clients.Group to simulate Clients.Caller,
Clients.Others, or Clients.OthersInGroup. In the following example, the MoveShapeHub class passes the
connection ID to the Broadcaster class so that the Broadcaster class can simulate Clients.Others.
//Forthecompleteexample,see
//http://www.asp.net/signalr/overview/signalr20/gettingstartedwithsignalr20/tutorial
serverbroadcastwithsignalr20
//ThissampleonlyshowscodethatpassesconnectionIDtothenonHubclass,
//inordertosimulateClients.Others.
publicclassMoveShapeHub:Hub
{
//CodenotshownputsasingletoninstanceofBroadcasterinthisvariable.
privateBroadcaster_broadcaster;
publicvoidUpdateModel(ShapeModelclientModel)
{
clientModel.LastUpdatedBy=Context.ConnectionId;
//Updatetheshapemodelwithinourbroadcaster
_broadcaster.UpdateShape(clientModel);
}
}
publicclassBroadcaster
{
publicBroadcaster()
{
_hubContext=GlobalHost.ConnectionManager.GetHubContext<MoveShapeHub>();
}
publicvoidUpdateShape(ShapeModelclientModel)
{
_model=clientModel;
_modelUpdated=true;
}
//CalledbyaTimerobject.
publicvoidBroadcastShape(objectstate)
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
25/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
{
if(_modelUpdated)
{
_hubContext.Clients.AllExcept(_model.LastUpdatedBy).updateShape(_model);
_modelUpdated=false;
}
}
}
groupName);
groupName);
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
26/27
8/10/2015
ASP.NETSignalRHubsAPIGuideServer(C#)|TheASP.NETSite
The following code in the Startup.cs file registers the module to run in the Hub pipeline:
publicvoidConfiguration(IAppBuilderapp)
{
GlobalHost.HubPipeline.AddModule(newLoggingPipelineModule());
app.MapSignalR();
}
There are many different methods that you can override. For a complete list, see HubPipelineModule Methods
http://msdn.microsoft.com/enus/library/jj918633v=vs.111.aspx .
This article was originally created on June 10, 2014
Author Information
Tom DykstraTom Dykstra is a Senior Programming Writer on Microsoft's Web Platform &
Tools Content Team...
Comments 14
This site is managed for Microsoft by Neudesic, LLC. | 2015 Microsoft. All rights reserved.
http://www.asp.net/signalr/overview/guidetotheapi/hubsapiguideserver
27/27