Let's say I have the following code running on a Windows service. I have to send data from a Windows service on a machine to a webpage that is open on the same machine(but not hosted on that machine).
static void Main(string[] args)
{
Int32 counter = 0;
while (counter < 100)
{
SendUDP("127.0.0.1", 49320, counter.ToString(), counter.ToString().Length);
Thread.Sleep(2000);
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);
}
I have to listen for the data sent to port 49320 and then process it in the browser.
I can create a listener on the webpage with Node.js like below, but I have to start this service separately and also install node.js on the client.
Is there any alternative to this? Something more lightweight ?
I could also create an AJAX to query a webservice every 2 seconds that would do the same thing as Windows Service, but it seems like a lot of queries sent all the time for nothing.
//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 49320
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(49320);