我有一个带socket.io的nodejs应用程序。 要对此进行测试,请将以下列表另存为app.js.安装节点,然后npm install 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。 (这是通过局域网,因此您无法访问。)
如何在nodejs中实现?
SensorMonkey是否可行?如果是这样,有关如何使用它的任何指示?
答案 0 :(得分:0)
我有一个正常工作的黑客,我请求读者评论......
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);
参考文献: