DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. Push Data in Real-time with SignalR

Push Data in Real-time with SignalR

Sony Arouje user avatar by
Sony Arouje
·
Oct. 04, 12 · Interview
Like (1)
Save
Tweet
Share
20.61K Views

Join the DZone community and get the full member experience.

Join For Free

we've all spent plenty of time refreshing our browsers to see the updated score of a cricket match or fresh stock details. so it's particularly cool when the browser can display updated data without a manual refresh. but how do you implement that functionality using .net technology? there's no straightforward approach, and most methods require loads of code.

so how do we achieve it? the answer is signalr . scott hanselman has a nice post about signalr. in his post, he explains a small chat application using 12 lines of code.

i wanted a real time pushing of data to asp.net, javascript client or desktop clients for a project i'm working on. i'll post the details of that project later. i was aware of signalr, but never really tried it, or doesn’t know how to make it work. yesterday i decided to write a tracer to better understand how signalr works. this post is all about the tracer i created.

tracer functionality

the functionality is very simple. i need two clients, a console, and a web app. data entered in any of these clients should reflect in other one. a simple functionality to test signalr.

let’s go through the implementation.

i have three projects in my solution 1. signalr self hosted server 2. a console client 3. a web application.

signalr server

here i used a self hosting option. that means i can host the server in console or windows service. have a look at the code.

using system;
using system.threading.tasks;
using signalr.hosting.self;
using signalr.hubs;
namespace net.signalr.selfhost
{
    class program
    {
        static void main(string[] args)
        {
            string url = "http://localhost:8081/";

            var server = new server(url);
            server.maphubs();
            
            server.start();
            console.writeline("signalr server started at " + url);

            while (true)
            {
                consolekeyinfo ki = console.readkey(true);
                if (ki.key == consolekey.x)
                {
                    break;
                }
            }
        }

        public class collectionhub : hub
        {
            public void subscribe(string groupname)
            {
                groups.add(context.connectionid, groupname);
                console.writeline("subscribed to: " + collectionname);
            }

            public task unsubscribe(string groupname)
            {
                return clients[groupname].leave(context.connectionid);
            }

            public void publish(string message, string groupname)
            {
                clients[groupname].flush("signalr processed: " + message);
            }
        }

    }
}

as you can see, i hosted the signalr server in a specific url. you can see another class called collectionhub inherited from hub. so what is a hub? hubs provide a higher level rpc framework, client can call the public functions declared in the hub. in the above hub i declared subscriber, unsubscribe and publish function. the clients can subscribe to messages by providing a collection name, it’s like joining to a chat room. only the members in that group receives all the messages.

you will notice another function called publish with a message and a groupname. the clients can call the publish method by passing a message and a group name. signalr will notify all the clients subscribed to that group with the message passed. so what’s this ‘ flush’ function called in publish, it’s nothing but the function defined in the client. we will see that later.

we are done, run the console application and our signalr server is ready to receive requests.

signalr clients

first we will look into a console client. let’s see the code first.

using signalr.client.hubs;
namespace net.signalr.console.client
{
    class program
    {
        static void main(string[] args)
        {
            var hubconnection = new hubconnection("http://localhost:8081/");
            var serverhub = hubconnection.createproxy("collectionhub");
            serverhub.on("flush", message => system.console.writeline(message));
            hubconnection.start().wait();
            serverhub.invoke("subscribe", "product");
            string line = null;
            while ((line = system.console.readline()) != null)
            {
                // send a message to the server
                serverhub.invoke("publish", line, "product").wait();
            }

            system.console.read();
        }
    }
}

let’s go line by line.

  1. create a hub connection with the url where signalr server is listening.
  2. create a proxy class to call functions in collectionhub we created in the server.
  3. register an event and callback, so that server can call client and notify updates. as you can the event name is ’flush’, if you remember the server calls this function in publish function to update the message to clients.
  4. start the hub and wait to finish the connection.
  5. we can call any public method in declared in hub using the invoke method by passing the function name and arguments.

run the console application and type anything and hit enter. you can see some thing like below.

image

the name prefixed ‘signalr processed’ is the message back from the signalr server. so we are done with a console application.

now how about we have to display the updates in a web application. let’s see how to do it in web application. in web application i used javascript to connect to the signalr server.

<html xmlns="http://www.w3.org/1999/xhtml">
    <script src ="scripts/json2.js" type="text/jscript"></script>
    <script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
    <script src="scripts/jquery.signalr-0.5.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
           $(function () {
               var connection = $.hubconnection('http://localhost:8081/');
               proxy = connection.createproxy('collectionhub')
               connection.start()
                    .done(function () {
                        proxy.invoke('subscribe', 'product');
                        $('#messages').append('<li>invoked subscribe</li>');
                    })
                    .fail(function () { alert("could not connect!"); });


               proxy.on('flush', function (msg) {
                   $('#messages').append('<li>' + msg + '</li>');
               });

               $("#broadcast").click(function () {
                   proxy.invoke('publish', $("#datatosend").val(), 'product');
               });

           });
    </script>
    <body>
        <div>
            <ul id="messages"></ul>
            <input type="text" id="datatosend" />
            <input id="broadcast" type="button" value="send"/>
        </div>
    </body>
</html>

you can install signalr javascript client from nuget and it will install all the required js files. the code looks very similar to the one in console application. so not explaining in detail.

now if you run all three application together and any update in one client will reflect in other. as you can see in web client we use javascript for dom manipulation, so the page will never refresh but you will see the updated info.

image

i hope this post might help you to get started with signalr.

dowload the source code .

happy coding…

Data (computing) application Console (video game CLI) push

Published at DZone with permission of Sony Arouje, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The Real Democratization of AI, and Why It Has to Be Closely Monitored
  • Apache Kafka Introduction, Installation, and Implementation Using .NET Core 6
  • Data Engineering Trends for 2023
  • Why the World Is Moving Towards Serverless Computing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: