How to send live data from a C# Desktop Application to Web using Websockets

This is a step-by-step guide about how to expose live data from a C# console application to a web browser using WebSockets. The example has been implemented and tested on Windows7.

NodeJs and Socket.IO installation

  1. Install node.js – http://nodejs.org/
  2. Install socket.io windows package – http://code.google.com/p/nodejs-win/downloads/list (attenzione a prendere la versione corretta compatibile con nodejs)
  3. Add to you Windows PATH nodejs directory- ;C:\Program Files\NodeJS
  4. Launch windows console (cmd) and then node application typing node, you should see the node prompt
C:\Users\roggero>node
>

to exit CTRL+C (twice)

Source Code

    • ws.js is the WebSocket Gateway and UDP server written in NodeJs
    • index.html, served by ws.js, visualizes the data
    • desktop.cs is the C# Console Application (Visual Studio 2010) that writes the data to UDP (a counter updated each 50ms)
        Source code can be downloaded here –

https://docs.google.com/open?id=0B4xZ7dwpphzxazR1WWR1WHBmQ1k
ws.js

//websocket gateway on 8070
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs');
var mysocket = 0;
app.listen(8070);
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }
    res.writeHead(200);
    res.end(data);
  });
}
io.sockets.on('connection', function (socket) {
  console.log('index.html connected'); 
  mysocket = socket;
});

//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
  console.log("msg: " + msg);
  if (mysocket != 0) {
     mysocket.emit('field', "" + msg);
     mysocket.broadcast.emit('field', "" + msg);
  }
});
server.on("listening", function () {
  var address = server.address();
  console.log("udp server listening " + address.address + ":" + address.port);
});
server.bind(41181);

index.html

<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
  var socket = io.connect('http://localhost');
  socket.on('field', function (data) {
    console.log(data);
    $("#field").html(data);
  });
</script>
  Data: <div id="field"></div>
</body>
</html>

Desktop.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace desktop
{
    class Desktop
    {
        // TODO: check all errors
        static void Main(string[] args)
        {
            Int32 counter = 0;
            while (true)
            {
                SendUDP("127.0.0.1", 41181, counter.ToString(), counter.ToString().Length);
                Thread.Sleep(50);
                counter++;
            }
        }
        public static void SendUDP(string hostNameOrAddress, int destinationPort, string data, int count)
        {
            IPAddress destination = Dns.GetHostAddresses(hostNameOrAddress)[0];
            IPEndPoint endPoint = new IPEndPoint(destination, destinationPort);
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            for (int i = 0; i < count; i++)
            {
                socket.SendTo(buffer, endPoint);
            }
            socket.Close();
            System.Console.WriteLine("Sent: " + data);
        }
    }
}

Run the demo

To run this demo:

  • Execute from cmd prompt: node ws.js
  • Execute desktop.exe application
  • Navigate with your modern web browser to http://localhost:8070
c:\Users\roggero\Desktop>node ws.j
   info  - socket.io started
udp server listening 0.0.0.0:41181

That’s all!

7 thoughts on “How to send live data from a C# Desktop Application to Web using Websockets

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