简体   繁体   English

如何使用socket.io请求实现类似jQuery的回调?

[英]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. 例如,当您使用JQuery发送ajax请求时,可以在回调函数中处理接收到的响应数据。

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

The typical function callback paradigm isn't necessarily the appropriate way to handle a response from the server when using socket.io. 使用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());
});

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

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