Communication between Node.js server and client
We are mostly electronic engineers with a background in C programming and some OOP experience. JavaScript is not our strong suit. So, when tasked with communicating data from a Node.js server with a client, many examples and well-developed tutorials weren’t so intuitive for me. In the end, I was able to cook up our first working example using socket.io. This example is probably filled with shameful coding, but it’s easily understandable for someone with my background.
Server script:
var http = require('http').createServer(serverAnswer);
var fs = require('fs');
var url = require('url');
var io = require('socket.io')(http);
http.listen(80);
console.log("Servidor andando");
var hSocket;
var intervalMuestras;
io.sockets.on('connection', function(socket){
hSocket = socket;
hSocket.on('start',function(canal){
console.log("Orden de Comenzar Adquisición recibida");
i=0;
intervalMuestras = setInterval(simularMuestreo, 1000);
});
hSocket.on('stop',function(){
console.log("Orden de Detener Adquisición recibida");
clearInterval(intervalMuestras);
});
});
var i;
function simularMuestreo(){
i++;
let muestras_json = JSON.stringify(i);
hSocket.emit('data',muestras_json);
}
// Función principal del servidor
var fs;
function serverAnswer(req,res){
var q = url.parse(req.url, true);
console.log(q.pathname);
console.log(q.search);
if(q.pathname == "/cliente.html"){
res.writeHead(200, {'Content-Type': 'text/html'});
content=fs.readFileSync('cliente.html');
res.write(content);
res.end();
}
else{
res.writeHead(404, {'Content-Type': 'text/html'});
res.end("404 Not Found!");
}
}
Client script:
<html>
<body>
<h1>Datos</h1>
<button onclick="buttonAcquire()">Adquirir</button>
<button onclick="buttonStop()">Stop</button>
<p id="display"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
var socket;
socket = io();
socket.on('data',manejadorDatosSocket);
function buttonAcquire(){
socket.emit('start',0);
}
function buttonStop(){
socket.emit('stop',0);
}
function manejadorDatosSocket(data){
muestras = JSON.parse(data);
console.log(muestras);
document.getElementById("display").innerHTML = muestras;
}
</script>
</body>
</html>