The tutorial demonstrates the following SignalR development tasks:
- Adding the SignalR library to an ASP.NET web application.
- Creating a hub class to push content to clients.
- Creating an OWIN startup class to configure the application.
- Using the SignalR jQuery library in a web page to send messages and display updates from the hub.
The following screen shot shows the chat application running in a browser. Each new user can post comments and see comments added after the user joins the chat.
Set up the Project
This section shows how to use Visual Studio 2013 and SignalR version 2.0 to create an empty ASP.NET web application, add SignalR, and create the chat application.
The following steps use Visual Studio 2013 to create an ASP.NET Empty Web Application and add the SignalR library:
- In Visual Studio, create an ASP.NET Web Application.
- In the New ASP.NET Project window, leave Empty selected and click Create Project.
- In Solution Explorer, right-click the project, select Add | SignalR Hub Class (v2). Name the classChatHub.cs and add it to the project. This step creates the ChatHub class and adds to the project a set of script files and assembly references that support SignalR.Note: You can also add SignalR to a project by opening the Tools | Library Package Manager | Package Manager Console and running a command:
install-package Microsoft.AspNet.SignalR
If you use the console to add SignalR, create the SignalR hub class as a separate step after you add SignalR. - In Solution Explorer, expand the Scripts node. Script libraries for jQuery and SignalR are visible in the project.
- Replace the code in the new ChatHub class with the following code.
using System; using System.Web; using Microsoft.AspNet.SignalR; namespace SignalRChat { public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } } }
- In Solution Explorer, right-click the project, then click Add | OWIN Startup Class. Name the new class
Startup
and click OK. - Change the contents of the new Startup class to the following.
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(SignalRChat.Startup))] namespace SignalRChat { public class Startup { public void Configuration(IAppBuilder app) { // Any connection or hub wire up and configuration should go here app.MapSignalR(); } } }
- In Solution Explorer, right-click the project, then click Add | HTML Page. Name the new page
index.html
. - In Solution Explorer, right-click the HTML page you just created and click Set as Start Page.
- Replace the default code in the HTML page with the following code.Note: A later version of the SignalR scripts may be installed by the package manager. Verify that the script references below correspond to the versions of the script files in the project.
<!DOCTYPE html> <html> <head> <title>SignalR Simple Chat</title> <style type="text/css"> .container { background-color: #99CCFF; border: thick solid #808080; padding: 20px; margin: 20px; } </style> </head> <body> <div class="container"> <input type="text" id="message" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"> </ul> </div> <!--Script references. --> <!--Reference the jQuery library. --> <script src="Scripts/jquery-1.6.4.min.js"" ></script> <!--Reference the SignalR library. --> <script src="/Scripts/jquery.signalR-2.0.0.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="/signalr/hubs"></script> <!--Add script to update the page and send messages.--> <script type="text/javascript"> $(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatHub; // Create a function that the hub can call to broadcast messages. chat.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); // Add the message to the page. $('#discussion').append('<li><strong>' + encodedName + '</strong>: ' + encodedMsg + '</li>'); }; // Get the user name and store it to prepend to messages. $('#displayname').val(prompt('Enter your name:', '')); // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); }); </script> </body> </html>
- Save All for the project.
Run the Sample
- Press F5 to run the project in debug mode. The HTML page loads in a browser instance and prompts for a user name.
- Enter a user name.
- Copy the URL from the address line of the browser and use it to open two more browser instances. In each browser instance, enter a unique user name.
- In each browser instance, add a comment and click Send. The comments should display in all browser instances.Note: This simple chat application does not maintain the discussion context on the server. The hub broadcasts comments to all current users. Users who join the chat later will see messages added from the time they join.The following screen shot shows the chat application running in three browser instances, all of which are updated when one instance sends a message:
- In Solution Explorer, inspect the Script Documents node for the running application. There is a script file named hubs that the SignalR library dynamically generates at runtime. This file manages the communication between jQuery script and server-side code.
Examine the Code
The SignalR chat application demonstrates two basic SignalR development tasks: creating a hub as the main coordination object on the server, and using the SignalR jQuery library to send and receive messages.
SignalR Hubs
In the code sample the ChatHub class derives from the Microsoft.AspNet.SignalR.Hub class. Deriving from theHub class is a useful way to build a SignalR application. You can create public methods on your hub class and then access those methods by calling them from scripts in a web page.
In the chat code, clients call the ChatHub.Send method to send a new message. The hub in turn sends the message to all clients by calling Clients.All.broadcastMessage.
The Send method demonstrates several hub concepts :
- Declare public methods on a hub so that clients can call them.
- Use the Microsoft.AspNet.SignalR.Hub.Clients dynamic property to access all clients connected to this hub.
- Call a function on the client (such as the
broadcastMessage
function) to update clients.public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } }
SignalR and jQuery
The HTML page in the code sample shows how to use the SignalR jQuery library to communicate with a SignalR hub. The essential tasks in the code are declaring a proxy to reference the hub, declaring a function that the server can call to push content to clients, and starting a connection to send messages to the hub.
The following code declares a reference to a hub proxy.
var chat = $.connection.chatHub;
Note: In JavaScript the reference to the server class and its members is in camel case. The code sample references the C# ChatHub class in JavaScript as chatHub.
The following code is how you create a callback function in the script. The hub class on the server calls this function to push content updates to each client. The two lines that HTML encode the content before displaying it are optional and show a simple way to prevent script injection.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
The following code shows how to open a connection with the hub. The code starts the connection and then passes it a function to handle the click event on the Send button in the HTML page.
Note: This approach ensures that the connection is established before the event handler executes.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});