Wednesday 8 February 2012

A minimal SignalR example

SignalR is an “async signaling library for .NET to help build real-time, multi-user interactive web applications”.

And its very cool. A minimal example…

Add the “SignalR” NuGet package to a web application:

Install-Package SignalR

The HTML:

<html>
<head>
</head>
<body>
<script src="../Scripts/jquery-1.6.4.js"></script>
<script src="../Scripts/jquery.signalR.js"></script>
<script src="../signalr/hubs"></script>
<form id="form1" runat="server">
<div>
<script type="text/javascript">
var chat;

$(function () {
// Created proxy
chat = $.connection.myChat;

// Assign a function to be called by the server
chat.addMessage = onAddMessage;

// Register a function with the button click
$("#broadcast").click(onBroadcast);

// Start the connection
$.connection.hub.start();
});

function onAddMessage(message) {
// Add the message to the list
$('#messages').append('<li>' + message + '</li>');
}

function onBroadcast() {
// Call the chat method on the server
chat.send($('#message').val());
}
</script>
<input type="text" id="message" />
<input type="button" id="broadcast" />
<ul id="messages"></ul>
</div>
</form>
</body>
</html>

The code (C#):

    using SignalR.Hubs;

public class MyChat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addMessage(message);
}
}

And that is it.

Now you have a real-time chat/message application. View the page in multiple browsers and see all the client receive all the messages in real-time.


About Me