简体   繁体   English

每10秒钟通过socket.io发送数据

[英]Send data every 10 seconds via socket.io

I'm trying to built a web-application which displays a dot on a map and update its position every 10seconds. 我正在尝试构建一个Web应用程序,该应用程序在地图上显示一个点并每10秒更新一次其位置。 The way I solved it right now is by polling a page via javascripts timeout every 10 seconds and parsing the result. 我现在解决的方法是每10秒通过javascript超时轮询一个页面并解析结果。 This works fine, but when having multiple browsers polling the same webpage the webserver resources spike, obviously. 这可以正常工作,但是很显然,当有多个浏览器轮询同一网页时,Web服务器资源会急剧增加。 Even when adding memcached as a intermediate. 即使在添加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. 它只在控制台中显示一次Hello World数据。 Instead of every second.... What is going wrong here? 而不是每一秒钟。...这里出了什么问题?

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);
});

改用javascript的setinterval方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM