node.js非阻塞POST请求,等待另一个POST请求

时间:2015-11-22 02:50:48

标签: javascript node.js multithreading post asynchronous

所以我正在开发一个基于文本的游戏,用户将post请求发送到用node.js编写的服务器。但是,我需要让第一个玩家在提交回复之前等待第二个玩家,将两个玩家匹配在一起。现在的问题是,在我调用一次post请求后,我无法发送任何响应的发布请求。似乎第一个线程阻止了更多的未来请求。在使用回调和异步方面应该做些什么。我不想在可能的情况下使用套接字,因为这会限制玩家可以编写的语言。

var canvas = document.createElement('canvas');
var w = canvas.width = 800,
   h = canvas.height = 600;
var c = canvas.getContext('2d');

var img = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';

var background = new Image();
background.src = "https://i2.wp.com/i2.listal.com/image/2669447/500full.jpg";



var position = {x : w/3.2, y : h/2.5};

document.body.appendChild(canvas);

var particles = [];
var random = function(min, max){
 return Math.random()*(max-min)*min;
};

/*canvas.onmousemove = function(e){
 position.x = e.offsetX;
 position.y = e.offsetY;
};*/
function Particle(x, y){
 this.x = x;
 this.y = y;
 this.velY = -2;
 this.velX = (random(1, 10)-5)/10;
 this.size = random(3, 5)/10;
 this.alpha = 1;
 this.update = function(){
   c.drawImage(background,0,0);
   this.y += this.velY;
   this.x += this.velX;
   this.velY *= 0.99;
   if(this.alpha < 0)
     this.alpha = 0;
   c.globalAlpha = this.alpha;
   c.save();
   c.translate(this.x, this.y);
   c.scale(this.size, this.size);
   c.drawImage(img, -img.width/2, -img.height/2);
   c.restore();
   this.alpha *= 0.96;
   this.size += 0.02;//
 };
}

var draw = function(){
 var p = new Particle(position.x, position.y);
 particles.push(p);

 while(particles.length > 500) particles.shift();

 c.globalAlpha = 2;
 c.drawImage(background,0,0);
 c.fillRect(0,0,w,h);



 for(var i = 0; i < particles.length; i++)
 {
   particles[i].update();
 }
};

setInterval(draw, 1000/60);

3 个答案:

答案 0 :(得分:1)

所以你可能已经发现,一旦你的等待功能开始,没有其他事情发生。这是因为带有阻塞调用的无限while循环(console.log)会阻止事件循环执行任何其他操作,直到它完成为止。您可以包括等待setTimeout,setInterval和clearInterval以在将来的某个时刻运行函数,在某个时间间隔上运行函数,并分别在某个时间间隔内停止运行函数。

var newGame = 0;

app.post('/game/join', function(req, res) {
    var username = req.body.username;
    var password = req.body.password;

    if (newGame === 1) {
        res.send('Game started' + username);
    } else {
        var wait = setInterval(function() {
            if (newGame === 1){
                clearInterval(wait);
                res.send('Game Started');
                newGame = 0;
            }
        }, 5000); // retry every 5 seconds
    }
}

});

答案 1 :(得分:0)

Node.js是单线程的,因此您的代码阻止您的服务器处理其他请求。阻止事件循环是你不想做的事情。

我打算请求使用像Socket.IO或WebRTC这样的东西,但我看到了你的约束。我不太确定你的意思是“限制语言玩家可以编码”

答案 2 :(得分:0)

对我来说,不清楚你如何挑选2个用户开始比赛。如果是这样,一个玩家连接而另一个玩家正在加入,然后在他们之间开始匹配,我会做这样的事情。

def makeRequestToSpotify(songname):

    encodedname = urllib.parse.quote_plus(songname)

    url = "https://api.spotify.com/v1/search?query=" + encodedname+ "&type=track"

    content = urllib.request.urlopen(url)

    data = json.loads(content.readall().decode('utf-8'))

    songLink = data["tracks"]["items"][0]["external_urls"]["spotify"]

    #print(songLink,"\n")
    link = songLink
    song = getMusicFilesFromFolder()


def getMusicFilesFromFolder(afolder):

    extensions = [".mp3",".wma",".aac",".m4a"]

    filenames = []
    for x in os.walk(afolder):
        for file in x[2]:
            file_name, filext = os.path.splitext(file)
            for ext in extensions:
                if filext == ext:
                    filenames.append(file_name)
                    break

    for file in filenames:

        makeRequestToSpotify(file)

    return filenames