我有一个带有socket.io的nodejs应用程序。要测试这一点,请将下面的清单另存为app.js。安装节点,然后npm安装socket.io,最后在命令提示符下运行: node app.js
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后,在浏览器中打开此文件。
<!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是一个可行的替代方案吗?如果是这样的话,有什么关于如何使用它的建议吗?
https://stackoverflow.com/questions/22345290
复制相似问题