This article explains how to broadcast a message on multiple browsers using SignalR in ASP.NET.
What SignalR is: SignalR is an ASP.Net server library for adding real-time functionality to a web application. This includes client libraries for JavaScript and other clients.
Getting Started
To get started with SignalR:
- Start Visual Studio
- Create a new website
- Provide the name and location of website
- Click "Next"
Install SignalR
Click "Tools" | "Library Package Manager" | "Package Manager Console" and run the command: "install-package Microsoft.AspNet.SignalR"
Or
Install using NuGet package Manager, right-click on "Project" and click on "Manage Nuget packages" and search for "SignalR" then click "Install".
As you can see, after installation, a few assemblies and scripts have been added to the bin and scripts folders.
Now to add the hub classes. If you are using ASP.Net 4.5 then you can see there are hub classes available in templates otherwise you need to add them manually.
Here is my hub class code.
//[HubName("employeeHub")]
public class EmployeeHub : Hub
{
//[HubMethodName("Send")]
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
// [HubMethodName("SendNotifications")]
public void SendNotifications(string message)
{
Clients.All.receiveNotification(message);
}
}
As you can see, the EmployeeHub class inherits the hub Hub so it is added to the namespace also.
using Microsoft.AspNet.SignalR;
Now let's work on the client code.
<body>
<input id="text1" type="text" />
<input id="button1" type="button" value="Send" />
<ul id="discussion">
</ul>
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-1.1.3.js" type="text/javascript"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.employeeHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.receiveNotification = function (message) {
// alert(" says '" + message + "'");
// Html encode display name and message.
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li>' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$("#button1").click(function () {
notifications.server.sendNotifications($("#text1").val());
}).fail(function (e) {
alert(e);
});
});
});
</script>
</body>
And now add one more line of code in the global file.
<%@ Import Namespace="System.Web.Routing" %>
// Register the default hubs route: ~/signalr
RouteTable.Routes.MapHubs();
We are now all set to see the output.
Open the result in multiple browsers.
Now put some text in any text box and click the "send" button.