简体   繁体   English

延迟是socket.io事件吗?

[英]Delay is socket.io event?

I created an ajax call to the IMBd database 我创建了对IMBd数据库的Ajax调用

 // API Key key = "4dba72b2-7558-4c0f-bd18-9ffcb0999c4e"; // Url mainUrl = "http://api.myapifilms.com/imdb/top?token="+ key +"&format=json&data=0&start=1&end=250"; // API Call var request = require('request'); request(mainUrl, function (error, response, body) { if (!error && response.statusCode == 200) { // Storing data in an object var obj = JSON.parse(body), //JSON Parser movieArray = obj.data.movies, //Creating Array item = movieArray[randomMovieRank]; //Setting random movie variable itermArray = [item.ranking,item.title,item.year]; console.log(itermArray); io.sockets.emit("serverAnswer", {ranking: itermArray[0], title: itermArray[1], year: itermArray}); } }); return false; 

Followed up by: 跟进:

 socket.on("serverAnswer", function(data){ console.log(data.title); }); 

The socket.on is called on the client side. 在客户端调用socket.on。 The problem I am having is that it is pulling through the data very slowly if at all. 我遇到的问题是,如果有的话,它正在非常缓慢地浏览数据。 The API is working as it is console logging correctly in terminal. 该API正在运行,因为它正在控制台中正确记录在终端中。 But client side it sometimes pulls through ad sometimes doesnt. 但是客户端有时却无法通过广告。 Is there something I am doing wrong? 我做错什么了吗?

EDIT: 编辑:

Added pastebin: http://pastebin.com/TYHsqBmK 添加了pastebin: http//pastebin.com/TYHsqBmK

When you invoke the emit method, your client is not guaranteed connected,you can trigger the ajax event after the client connected or emit specified messages,such as 调用发出方法时,不能保证客户端已连接,可以在客户端连接后触发ajax事件或发出指定的消息,例如

the server : 服务器

io.on('connection',function(socket){
    if(movies !== null)
    {
        socket.emit("serverAnswer", {movies:movies});
    }
    else{
        //1.ajax request IMDB resource
        //2.set movies variables
        //3.emit message
    }
});

the client: 客户端:

socket.on("serverAnswer", function(data){
        console.log(data);
    });

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

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