我想创建一个函数,快速服务器将发送到客户端(python),python 会做一些事情并将结果发送回服务器。服务器将等待客户端发出的结果并将该结果返回给前端。如果过了一段时间,python 仍然没有发出任何东西,快递服务器会告诉前端没有收到任何结果。我可以使用承诺并设置超时来等待来自 python 的发送消息吗?
答案 0 :(得分:0)
应该问题不大。请参阅 socket.io 文档中的 Acknowledgments。他们甚至有一个超时的例子:
// express server endpoint
app.get('/somethingcool', (req, res) => {
// assuming socket will be the client socket of the python server
socket.emit("do_something_i_will_wait", {/* data */}, withTimeout((response) => {
console.log("success!");
res.status(200).send(response);
}, () => {
console.log("timeout!");
res.status(500).send("python took to long to reply");
}, 5000));
});
// helper function for timeout functionality
const withTimeout = (onSuccess, onTimeout, timeout) => {
let called = false;
const timer = setTimeout(() => {
if (called) return;
called = true;
onTimeout();
}, timeout);
return (...args) => {
if (called) return;
called = true;
clearTimeout(timer);
onSuccess.apply(this, args);
}
}
所以我们从服务器向客户端发出一些简单的东西,作为最后一个参数,我们将放置一个函数 - 这将是我们的确认函数。
// server
socket.emit("ferret", "tobi", (data_from_client) => {
console.log(data_from_client); // data will be "woot"
});
在客户端,它看起来像这样。我们为事件侦听器“ferret”设置的回调有 2 个参数,我们从服务器传递到客户端的数据,以及我们的确认函数。
// client
client.on("ferret", (name, fn) => {
fn("woot");
});
我知道 socket.io 文档中的 withTimeout
示例可能有点难以理解,所以这里有一个不太复杂的示例,它的基本作用相同:
app.get('/somethingcool', (req, res) => {
let got_reply = false;
const timeout = setTimeout(() => {
if (got_reply) { return; }
got_reply = true;
res.status(500).send("too late");
}, 5000);
socket.emit("do_something_i_will_wait", {}, (reply) => {
if (got_reply) { return };
got_reply = true;
clearTimeout(timeout);
res.status(200).send(reply);
});
});