SignalR is an open source framework allowing bi-directional communication between client and server. Basically, it uses a stack of technologies; the idea being that the Signalr framework will establish the “best” way to maintain a bi-directional data stream, starting with web sockets, and falling all the way back to simply polling the server.
The following gives the basics of establishing a web site that can accept Signalr, and a console app that can send messages to it.
Create project
Let’s go MVC:
Hubs
Hubs are the way in which the Signalr service communicates with its clients. Obviously, the term service here may not actually represent a service.
To add a hub class, select the project, right-click and “New Item..“:
This adds the file, along with new references:
The code above that gets added is:
public void Hello()
{
Clients.All.hello();
}
Clients.All returns a dynamic type, so we lose intellisense at this point. It’s important that the signature of this method is exactly correct, and that it is decorated with the name of the hub, and that it is decorated with the name of the hub; so let’s replace with:
[HubName("MyHub1")]
public class MyHub1 : Hub
{
public void Hello(string message)
{
Clients.All.Hello(message);
}
}
Change Startup.cs:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR();
}
}
For all this to actually do anything, the next thing to do is hook up the JavaScript:
$(function () {
// Declare a proxy to reference the hub.
var hub = $.connection.MyHub1;
// Create a function that the hub can call to broadcast messages.
hub.client.hello = function (message) {
alert("Hello");
};
$.connection.hub.start()
.done(function () { console.log("MyHub1 Successfully Started"); })
.fail(function () { console.log("Error: MyHub1 Not Successfully Started"); })
});
Effectively, once we receive a message, we’re just going to display an alert. Once the event handler is wired up, we try to start the hub.
Next, reference the required files in BundleConfig.cs:
bundles.Add(new ScriptBundle("~/bundles/signalr").Include(
"~/Scripts/jquery-3.1.1.min.js").Include(
"~/Scripts/jquery.signalR-2.2.1.js"));
These are referenced in _Layout.cshtml; remember also that, because SignalR references Jquery, you’ll need to remove other references to Jquery:
[code lang=“HTML”]