Cole
Cole

Reputation: 33

How to wait for client response with socket.io?

I'm working on an online, turned based game in order to teach myself Node.js and Socket.IO. Some aspects of the game are resolved serverside. At one point during one of these functions, the server may require input from the clients. Is there a way I can "pause" the resolution of the server's function in order to wait for the clients to respond (via a var x = window.prompt)?

Here's an idea of the code I'm working with:

Server:

for (some loop){
  if (some condition){
   request input via io.sockets.socket(userSocket[i]).emit('requestInput', data)  
  }
}

Client:

socket.on('requestInput', function (data) {
  var input = window.prompt('What is your input regarding ' + data + '?');
  //send input back to the server
  socket.emit('refresh', input)  
});

Any thoughts?

Upvotes: 3

Views: 6332

Answers (2)

vaibhavmande
vaibhavmande

Reputation: 1111

I don't think that is possible.

for (some loop){
    if (some condition){
    request input via io.sockets.socket(userSocket[i]).emit('requestInput', data) 
    /* Even if you were able to pause the execution here, there is no way to resume   it when client emits the 'refresh' event with user input */
}

}

What you can do instead is emit all 'requestInput' events without pausing and save all responses you will get in socket.on('refresh',function(){}) event in an array, then you can process this array later. I don't know what your exact requirement is but let me know if that works.

Upvotes: 1

Ari
Ari

Reputation: 3669

Since you are emitting socket.emit('refresh', input) on the client side, you just need to set up a socket event listener on the server side as well. For example:

io.sockets.on('connection', function (socket) {
  socket.on('refresh', function (data) {
    console.log(data) //input
  });
})

I will also point out, so that you don't run into trouble down the line, that indefinite loops are a big nono in node. Nodejs runs on a single thread so you are actually blocking ALL clients as long as your loop is running.

Upvotes: 1

Related Questions