我下面有代理 WebSocket 连接的代码:
app.ws("/", async (socket) => {
api = new WebSocket("wss://example.com/?v=2", [], {
headers: {
"Origin": "https://example.com"
}
});
api.on("open", async () => {
api.on("message", async data => socket.send(data.toString()));
socket.on("message", async data => (api.readyState === api.OPEN) && api.send(data));
});
});
但有时我会收到此错误:
C:\Users\admin\project\app.js:64
socket.on("message", async data => (api.readyState === api.OPEN) && api.send(data));
^
TypeError: api.send is not a function
有没有办法在不使用 try catch 块的情况下解决这个问题?如果您能提供帮助,请用示例代码评论解决方案!
也许您可以确保 api 对象在尝试通过它发送消息之前已完全初始化并准备就绪。您可以通过在设置 socket.on("message") 处理程序之前检查 WebSocket 连接的就绪状态来完成此操作。像这样的东西应该有效,
app.ws("/", async (socket) => {
let api;
api = new WebSocket(
...
)
// wait for the WebSocket connection to open
await new Promise(resolve => {
api.on("open", resolve)
})
// then once the connection is open, set up the message handlers
api.on("message", data => {
socket.send(data.toString())
})
socket.on("message", data => {
if (api.readyState === api.OPEN) {
api.send(data);
} else {
// handle the case where the WebSocket connection is not open
console.error("WebSocket connection is not open.")
}
})
})