Stay Hungry,Stay Foolish!

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);
}
});
 

 

 

posted @ 2024-12-04 22:54  lightsong  阅读(3)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel