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


<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">
<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

// Start the connection

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

function onBroadcast() {
// Call the chat method on the server
<input type="text" id="message" />
<input type="button" id="broadcast" />
<ul id="messages"></ul>

The code (C#):

    using SignalR.Hubs;

public class MyChat : Hub
public void Send(string message)
// Call the addMessage method on all clients

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