I'm trying to built a web-application which displays a dot on a map and update its position every 10seconds. The way I solved it right now is by polling a page via javascripts timeout every 10 seconds and parsing the result. This works fine, but when having multiple browsers polling the same webpage the webserver resources spike, obviously. Even when adding memcached as a intermediate.
我正在尝试构建一个Web应用程序,它在地图上显示一个点并每隔10秒更新一次它的位置。我现在解决它的方法是每隔10秒通过javascripts超时轮询页面并解析结果。这很好,但是当有多个浏览器轮询同一个网页时,网络服务器资源显然会飙升。即使添加memcached作为中间件。
My next thought was of instead polling the page with the latest positional information every 10 seconds, just create a open socket and send new data over it.
我的下一个想法是每隔10秒使用最新的位置信息轮询页面,只需创建一个打开的套接字并通过它发送新数据。
So after a search I stumbled upon socket.io which should do exactly what I want, but I'm not getting it to work.
所以在搜索之后我偶然发现了socket.io,它应该完全符合我的要求,但我没有让它工作。
Even a basic thing like the following doesn't work; it just show the hello world data in the console once. Instead of every second.... What is going wrong here?
即使像以下这样的基本内容也不起作用;它只是在控制台中显示一次hello world数据。而不是每一秒......这里出了什么问题?
server
var io = require('socket.io').listen(1332);
io.sockets.on('connection', function (socket) {
setTimeout(function(){
sentPosition(socket);
}, 1000);
});
function sentPosition(socket){
socket.emit('position', {
hello: 'world'
});
}
Browser
var socket = io.connect('http://myserver.com:8080');
socket.on('position', function (data) {
console.log(data);
});
1 个解决方案
#1
2
use javascript's setinterval method instead
改用javascript的setinterval方法
#1
2
use javascript's setinterval method instead
改用javascript的setinterval方法