Kourindou Hime
Kourindou Hime

Reputation: 167

How to implement jQuery-like callbacks with socket.io requests?

What is the best way to implement this pseudocode? For example, when you send an ajax request with JQuery and you can process the received response data in a callback function.

socket.emit(<request data>, function(response_data) { ... });

Upvotes: 0

Views: 171

Answers (1)

AesopWaits
AesopWaits

Reputation: 21

The typical function callback paradigm isn't necessarily the appropriate way to handle a response from the server when using socket.io. Think of it as two-way communication. A message is sent with an event name and then processed on the server with a corresponding event handler. The server then emits an event back to the client with the response data.

For example:

Client code:

socket.on("ServerSentTime",function(timeData){ //Event Handler For Server Response
   console.log(timeData); 
});


socket.emit("AskServerForTime");     //Event Fired To Server

Server code:

socket.on("AskServerForTime",function() //Event Handler Awaits Client Request
{
   socket.emit("ServerSentTime", new Date().getTime());
});

Upvotes: 1

Related Questions