Acknowledgements of Socket.IO
https://socket.io/docs/v4/emitting-events/#Acknowledgements
Acknowledgements
Events are great, but in some cases you may want a more classic request-response API. In Socket.IO, this feature is named acknowledgements.
You can add a callback as the last argument of the
emit()
, and this callback will be called once the other side acknowledges the event:Server
io.on("connection", (socket) => {
socket.on("update item", (arg1, arg2, callback) => {
console.log(arg1); // 1
console.log(arg2); // { name: "updated" }
callback({
status: "ok"
});
});
});Client
socket.emit("update item", "1", { name: "updated" }, (response) => {
console.log(response.status); // ok
});With timeout
Starting with Socket.IO v4.4.0, you can now assign a timeout to each emit:
socket.timeout(5000).emit("my-event", (err) => {
if (err) {
// the other side did not acknowledge the event in the given delay
}
});You can also use both a timeout and an acknowledgement:
socket.timeout(5000).emit("my-event", (err, response) => {
if (err) {
// the other side did not acknowledge the event in the given delay
} else {
console.log(response);
}
});
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。