Quantcast
Channel: ASP.NET Blog
Viewing all articles
Browse latest Browse all 7144

SignalR: Building real time web applications

$
0
0

Note: This sample is targeting 1.0RC1, I will update the post after RTM is released

SignalR offers a simple and clean API to write real time web applications where the server needs to continuously push data to clients. Common applications are chat, news feed, notifications, multiplayer games.

In this sample, I demonstrate powerful features like:

  • A server implementation hosted in IISExpress
  • Client implementations running on IISExpress, a Console Application, and a Windows Store App
  • Doing request/response operations sync and async
  • Server pushing broadcast messages to ALL clients
  • Server pushing group messages to specific devices like a web browser, a desktop, or a tablet.

Server

Server derives the Hub class, and it handles incoming requests in two ways:

  1. Method "y Request(x)" transparently sends a response to client
  2. Method "void RequestAsync(x)" uses Clients.Caller.<DynamicMethod> to send a response to client

Server is also pushing data to clients in two ways:

  1. hubContext.Clients.All.<DynamicMethod>
  2. hubContext.Clients.Group(groupName).<DynamicMethod>

As you can see, dynamic methods define the events that need to be handled on the client side. Think of them as if they were interface methods to execute remote calls.

 

namespace SignalR.Sample
{
  public class SampleHub : Hub
  {     
    public static void Start()
    {
      ThreadPool.QueueUserWorkItem(_ =>
      {
      IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<SampleHub>();

hubContext.Clients.All.Broadcast(data); hubContext.Clients.Group("WebApp").Group(string.Format("WebApp {0}", DateTime.Now)); }); } public FromServerToClientData Request(FromClientToServerData request) { FromServerToClientData response = new FromServerToClientData(); response.Text = "Responding to: " + request.Text; return response; } public void RequestAsync(FromClientToServerData request) { FromServerToClientData response = new FromServerToClientData(); response.Text = "Responding to: " + request.Text; Thread.Sleep(TimeSpan.FromSeconds(5)); Clients.Caller.ResponseAsync(response); } public void JoinGroup(string groupName) { Groups.Add(Context.ConnectionId, groupName); } } }

Client

To write a client, you must define how to handle Server <DynamicMethods>: "client.Broadcast", "client.Group", and "client.ResponseAsync".

Then, client is started, and after the connection succeeds, the client can make requests to server by invoking "server.requestAsync" and "server.joinGroup".

You will see similar patterns in the ConsoleApp and WindowsStoreApp clients.

$(function () {
  $.connection.sampleHub.client.Broadcast = function(value) {
    $('#BroadcastTextArea').html('<pre>Broadcast: ' + value.Now + ' ' + value.Integer + 
' ' + value.Text + '</pre>'); } $.connection.sampleHub.client.Group = function (value) { $('#GroupTextArea').html('<pre>Group: ' + value + '</pre>'); } $.connection.sampleHub.client.ResponseAsync = function (value) { $('#ResponseAsyncTextArea').html('<pre>ResponseAsync: ' + value.Text + '</pre>'); } $.connection.hub.logging = true; $.connection.hub.start().done(function () { var request = new Object(); request.Text = 'This is a request from a WebApp!' $.connection.sampleHub.server.request(request).done(function (response) { $('#ResponseTextArea').html('<pre>Response: ' + response.Text + '</pre>'); }); $.connection.sampleHub.server.requestAsync(request); $.connection.sampleHub.server.joinGroup('WebApp'); }); });

There is more information about how I wrote the code when running the sample, simply follow these instructions:

  1. Download and extract SignalR.Sample.zip
  2. On Visual Studio 2012, open SignalR.Sample.sln
  3. Right-click the solution and select "Set Startup Projects…"
  4. Select "Multiple startup projects", and set the projects in this order:
  • SignalR.Sample
  • SignalR.Sample.Client
  • SignalR.Sample.WinRTClient
  • Set "Action" column in all projects to "Start". Click OK.
  • Ctrl-F5 to run the projects, it will start a browser, a console app, and a windows store app.
  • There are more advanced samples in the SignalR source code repository, follow these steps to get them:

    1. Install the latest Git for Windows
    2. Open a Command Prompt, create a folder, and download source code

    md C:\SignalR\release
    cd C:\SignalR\release
    git clone -b release https://github.com/SignalR/SignalR.git .
    1. On Visual Studio 2012, open C:\SignalR\release\Microsoft.AspNet.SignalR.sln

    SignalR has recently shipped as RC, more details here. For the RTM version, I want to post a more complex sample, my idea is to demonstrate how to publish the server implementation on Azure and use scale-out with Service Bus. Please post a comment if you are interested to see something else.


    Viewing all articles
    Browse latest Browse all 7144

    Trending Articles



    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>