SignalR 2.0 Persistent Connection Another Example, Tracking your Mouse Pointer.

This example uses SignalR 2.0 and track the position of the mouse’s pointer in a web browser.

tracking

Create a new project in Visual Studio 2013 choose the template ASP.NET Web Application, then Empty template.

First you need to add the libraries, open Tools\Library Packet Manager\Packet Manager Console and run the following:
Install-Package Microsoft.AspNet.SignalR

As in previous posts you don’t need to register a route using a Global.asax file.
You need to add an OWIN Startup Class. Add, New Item… and select Owin Start Class. Name it Startup.cs

using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(TrackingConnections.Startup))]

namespace TrackingConnections
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Map the TrackerConnection PersistentConnection to "/tracker"
            app.MapConnection<TrackerConnection>("/tracker");
        }
    }
}

Then the Client code, add a HTML file call it Index.html
To create dummy text I used a Chrome Extension called “Lorem Ipsum Generator”. You put the number of paragraphs in this case 4 and don’t forget to click the button “Save settings”

lorem

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.6.4.min.js"></script>
    <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
    <script src="Scripts/tracking.js"></script>
    <style>
        .client {
            position: absolute;
            background-color: white;
            -moz-box-shadow: 10px 10px 5px #888;
            -webkit-box-shadow: 10px 10px 5px #888;
            box-shadow: 3px 3px 3px #888;
            border: 1px solid #a0a0a0;
        }
    </style>
</head>
<body>
    <h1>Lorem Ipsum</h1>
    <p>Turpis parturient, in risus odio velit hac, tristique nascetur magna, dapibus non, et mus sociis nunc rhoncus ridiculus! Placerat, habitasse? Dictumst pulvinar! Nec arcu, pulvinar adipiscing et vut montes augue urna aliquam amet, enim! Augue, porta sociis enim! Non ut tristique et sed adipiscing, amet porttitor cursus risus, ac duis in porttitor? Lorem vel sed est vel nisi aenean turpis, dolor scelerisque diam mus, facilisis ut mauris risus in porttitor dignissim hac, duis nec quis sed! Tincidunt non turpis placerat, est, risus cum? A risus est porttitor rhoncus, ac et! Ridiculus magnis amet enim! A lorem, magna enim, mus eros. Vel hac cras lundium porta pulvinar enim platea sit aliquet, enim platea? Eros purus mus, augue, in scelerisque odio elit.</p>
    <p>Dis integer hac, in lacus, magnis ac aenean in, dolor placerat! Massa cum, in porta parturient, facilisis et lacus mid elit mid est. A urna. Ac elit etiam dis, cras non lectus porta? Elementum sociis, dignissim sed, nunc platea sit urna etiam elementum odio dictumst montes urna! Magnis, sed? Parturient! Duis rhoncus et pulvinar adipiscing! In porta, augue mid! Adipiscing pellentesque velit placerat enim nec, a, vel platea ac penatibus lectus? Dapibus augue et risus? Porttitor est nascetur hac sit dictumst! Pulvinar placerat? Lacus nascetur turpis? Porta! Nisi scelerisque! Montes sagittis penatibus magnis scelerisque? Urna, lacus augue lorem integer et elementum adipiscing porta cursus turpis sit integer, dis est massa urna? Turpis placerat vel cras nec elementum cursus vel.</p>
    <p>Urna ac, scelerisque urna nisi! Phasellus? Porta, nisi enim a ut! Nascetur turpis, eros! Tempor vel aenean, sociis magnis porttitor mid sit dictumst, hac parturient magnis odio, phasellus adipiscing, magna et, in ac cursus! Urna ut a et! Nisi magna nisi ac, a, amet phasellus. Nec ac? Magna hac, lundium rhoncus egestas augue ridiculus mattis a auctor pellentesque porttitor? Nisi ut diam velit pulvinar, sit ultrices sed phasellus et sagittis? Porttitor? Scelerisque nec urna aliquet tortor odio massa integer, dapibus porttitor porttitor pid mus! Et scelerisque nec magna sociis, aliquam adipiscing dolor ultrices magna mid dolor nec elementum platea, adipiscing aenean, penatibus urna purus, eros integer? Porttitor. In dapibus. Integer platea? A placerat non ridiculus. Enim, hac ac aliquet.</p>
    <p>Augue cursus, integer, augue, dignissim! Placerat lundium turpis quis lundium sociis duis, duis? Elementum, purus lundium nunc, non tortor sociis massa massa tristique scelerisque facilisis penatibus nisi proin vel lacus, platea. Tincidunt amet turpis, penatibus, in arcu ultrices tincidunt magna mid amet urna dis, ac hac, elementum dis turpis, ut nisi scelerisque dictumst cum magnis etiam proin, integer sagittis. Lacus, dolor est, scelerisque? Lectus dis dis risus rhoncus vel velit nisi. Sit sed adipiscing pellentesque, a sociis cras et magna facilisis a risus sed? A purus elit cursus egestas, magna amet cras velit mus, ultricies, adipiscing sed tortor. Arcu vut auctor, cum etiam, nisi vel mus dictumst, cras vut cum ac. Dapibus quis? Phasellus rhoncus urna. Rhoncus phasellus in.</p>
</body>
</html>

Add a JavaScript file and name it Tracking.js

/* SignalR Client */
var connection = $.connection("/tracker");
connection.start(function () {
    startTracking();
});
connection.received(function (data) {
    data = JSON.parse(data);
    var domElementId = "id" + data.id;
    var elem = createElementIfNotExists(domElementId);
    $(elem).css({ left: data.x, top: data.y }).text(data.id);
});

function startTracking() {
    $("body").mousemove(function (e) {
        var data = { x: e.pageX, y: e.pageY, id: connection.id };
        connection.send(JSON.stringify(data));
    });
}

/* Helper functions */
function createElementIfNotExists(id) {
    var element = $("#" + id);
    if (element.length == 0) {
        element = $("<span class='client' id='" + id + "'></span>");
        var color = getRandomColor();
        element.css({ backgroundColor: getRgb(color), color: getInverseRgb(color) });
        $("body").append(element).show();
    }
    return element;
}

function getRgb(rgb) {
    return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
}

function getInverseRgb(rgb) {
    return "rgb(" + (255 - rgb.r) + "," +
                    (255 - rgb.g) + "," +
                    (255 - rgb.b) + ")";
}

function getRandomColor() {
    return {
        r: Math.round(Math.random() * 256),
        g: Math.round(Math.random() * 256),
        b: Math.round(Math.random() * 256),
    };
}

And the last piece of code, the server code. Add a class and name it TrackerConnection.cs

using Microsoft.AspNet.SignalR;

namespace TrackingConnections
{
    public class TrackerConnection: PersistentConnection
    {
        //public static void InitRoute()
        //{
        //    RouteTable.Routes.MapConnection<TrackerConnection>(
        //        name: "tracker", url: "/tracker");
        //}

        protected override System.Threading.Tasks.Task OnReceived(IRequest request, string connectionId, string data)
        {
            return Connection.Broadcast(data, connectionId);
        }
    }
}

Run the code in multiple browsers and move your mouse to see how it moves in the other browser’s windows.

This example comes from the book SignalR by J.M.Aguilar, highly recommended.

Advertisements
This entry was posted in SignalR and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s