我不确定我要实现的目标是否是正确的方法,因为我找不到任何示例。
我有一个应用程序正在显示 Google map 和上面的多个对象。我希望对象的位置每隔 2 秒或 2 自动更新一次。
我正在考虑让一个带有 setInterval()
的 nodejs 服务器每 2 秒触发一次,以向不同的服务器执行 API 请求,获取数据响应并将其广播到所有套接字.io 客户端。
这是我目前正在使用的 server.js
:
var express = require('express'),
server = express(),
port = 3700,
host = 'localhost',
io = require('socket.io').listen(server.listen(port, host));
server
.get('/', function(req, res){
res.send('OK');
});
io.sockets.on('connection', function(socket){
console.log('connection started');
// Update the server date every seconds
setInterval(function(){
socket.emit('date', {'date': new Date()});
}, 1000);
// Update locations every minutes
setInterval(function(){
console.log('Client: ' + socket.id);
io.sockets.emit('update_locations', []);
}, 1000);
});
io.sockets.on('disconnect', function(socket){
console.log('Client "' + socket.id + '" disconnected');
});
查看我要广播 update_locations
消息的位置。
我正在研究应该如何执行对我的 API 的请求?
- 我的做法是否正确?
- 我应该在我的
setInterval()
函数中使用http.get()
吗? - 我应该使用
setInterval()
吗?如果没有setInterval()
,我不知道我将如何做到这一点
加油, 马克西姆
最佳答案
我正在详细回答我自己的问题:
我要感谢 Lellansin 为我指明了正确的方向:
这是我的server.js
:
var express = require('express'),
debug = true,
http = require('http'),
_ = require('underscore'),
server = express(),
port = 3700,
api_host = 'api.acme.local',
io = require('socket.io').listen(server.listen(port), {log: debug});
console.log('Node server listening on port', port);
io.set('log level', 1);
server
.get('/', function(req, res){
res.send('OK');
});
var clients = {};
io.sockets.on('connection', function(socket){
console.log('Client ' + socket.id + ' is connected');
// Add the client to the list of connected clients
clients[socket.id] = true;
// Broadcast to everyone the list of connected clients
io.sockets.emit('connected_clients', _.size(clients));
// Send the current positions to the connected client when client is ready
socket.on('ready', function() {
getCourses(function(data){
console.log('Send locations to client ' + socket.id);
socket.emit('update_locations', data);
});
});
// When a client is disconnecting, inform other clients
socket.on('disconnect', function() {
delete clients[socket.id];
console.log('Client "' + socket.id + '" disconnected');
io.sockets.emit('connected_clients', _.size(clients));
});
});
// Update locations every minutes
setInterval(function()
{
// Do nothing if there is no client
if (_.size(clients) == 0) {
return;
}
console.log('Update positions...');
// Get the current courses and broadcast them to all clients
getCourses(function(data){
io.sockets.emit('update_locations', data);
});
}, 60000); // every minute
// Update the server date every seconds
setInterval(function(){
io.sockets.emit('date', {'date': new Date()});
}, 1000);
function getCourses(callback)
{
var options = {
hostname: api_host,
port: 80,
path: '/courses',
method: 'GET'
};
var req = http.request(options, function(res) {
//console.log('-----------------------------------------');
//console.log('STATUS: ' + res.statusCode);
//console.log('HEADERS: ' + JSON.stringify(res.headers));
var output = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function() {
var obj = JSON.parse(output);
if (callback != undefined){
callback(obj);
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
如果至少有一个客户端连接,我只会广播数据。我不知道为什么这不是一个好主意,但我会感谢任何批评者。此外,在我看来,如果我在服务器端有多个 API 请求,它会开始变得难以阅读。
关于node.js - 使用 socket.io 从 API 向客户端广播 GET 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23650905/