首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在nodejs中通过TCP/IP获取传感器数据?

如何在nodejs中通过TCP/IP获取传感器数据?
EN

Stack Overflow用户
提问于 2014-03-12 16:00:01
回答 1查看 14.2K关注 0票数 2

我有一个带有socket.io的nodejs应用程序。要测试这一点,请将下面的清单另存为app.js。安装节点,然后npm安装socket.io,最后在命令提示符下运行: node app.js

代码语言:javascript
复制
var http = require('http'),
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);

// Send current time to all connected clients
function sendTime() {
    io.sockets.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 5000);

// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
    socket.emit('welcome', { message: 'Welcome!' });

    socket.on('i am client', console.log);
});

app.listen(3000);

这段代码将数据发送到文件index.html。运行app.js后,在浏览器中打开此文件。

代码语言:javascript
复制
<!doctype html>
<html>
    <head>
        <script src='http://code.jquery.com/jquery-1.7.2.min.js'></script>
        <script src='http://localhost:3000/socket.io/socket.io.js'></script>
        <script>
            var socket = io.connect('//localhost:3000');

            socket.on('welcome', function(data) {
                $('#messages').html(data.message);

                socket.emit('i am client', {data: 'foo!'});
            });
            socket.on('time', function(data) {
                console.log(data);
                $('#messages').html(data.time);
            });
            socket.on('error', function() { console.error(arguments) });
            socket.on('message', function() { console.log(arguments) });
        </script>
    </head>
    <body>
        <p id='messages'></p>
    </body>
</html>

现在发送的数据是当前时间,index.html工作正常,每五秒更新一次时间。

我想修改代码,以便它通过TCP读取我的传感器数据。我的传感器通过数据采集系统连接,并通过IP: 172.16.103.32端口:7700中继传感器数据。(这是通过LAN进行的,因此您无法访问。)

如何在nodejs中实现?

SensorMonkey是一个可行的替代方案吗?如果是这样的话,有什么关于如何使用它的建议吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22345290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档