Wednesday 12 March 2014

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
1
2
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 -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
1
2
3
c:\Users\roggero\Desktop>node ws.j
   info  - socket.io started
udp server listening 0.0.0.0:41181
That’s all!


No comments:

Post a Comment