How to get sensor data over TCP/IP in nodejs?

前端 未结 1 829
轻奢々
轻奢々 2021-01-01 08:32

I have a nodejs app with socket.io. To test this, save the below listing as app.js. Install node, then npm install socket.io and finally run on command prompt: node app.

相关标签:
1条回答
  • 2021-01-01 08:56

    I have a decent hack that is working right now, for which I request the readers to comment on....


    var net = require('net'),
    http = require('http'),
    port = 7700,                    // Datalogger port
    host = '172.16.103.32',         // Datalogger IP address
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');
    
    // Send index.html to all requests
    var app = http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(index);
    });
    
    // Socket.io server listens to our app
    var io = require('socket.io').listen(app);
    
    // Emit welcome message on connection
    io.sockets.on('connection', function(socket) {
        socket.emit('welcome', { message: 'Welcome!' });
    
        socket.on('i am client', console.log);
    });
    
    //Create a TCP socket to read data from datalogger
    var socket = net.createConnection(port, host);
    
    socket.on('error', function(error) {
      console.log("Error Connecting");
    });
    
    socket.on('connect', function(connect) {
    
      console.log('connection established');
    
      socket.setEncoding('ascii');
    
    });
    
    socket.on('data', function(data) {
    
      console.log('DATA ' + socket.remoteAddress + ': ' + data);
      io.sockets.emit('livedata', { livedata: data });        //This is where data is being sent to html file 
    
    });
    
    socket.on('end', function() {
      console.log('socket closing...');
    });
    
    app.listen(3000);
    

    References:

    1. Socket.io Website - www.socket.io - Its the buzzword now.
    2. TCP Socket Programming
    3. Nodejs "net" module
    4. Simplest possible socket.io example.
    0 讨论(0)
提交回复
热议问题