提问人:Neuropacman 提问时间:11/16/2023 更新时间:11/16/2023 访问量:16
Socket.IO 在环路中断开和重新连接
Socket.IO disconnecting and reconnnecting in loop
问:
我有一个运行 socket.io 的 nodejs 服务器来上传文件。我的客户端 (Python) 正在尝试遍历文件目录,并异步上传它们。虽然,在循环执行时,我看到套接字连接随机断开和重新连接,如以下日志所示:
似乎问题可能与资源有关,因为循环开始按预期非常快速地执行,然后断开连接。此外,我的循环异步上传每个文件,因此客户端/服务器/套接字的并发连接可能太多?
这是我的 Python 客户端代码:
async def upload_dataset(self, directory, connection_id, order_id, aes_key):
"""Upload a dataset to the server
:param str directory: Path to dataset folder to be uploaded.
:param str connection_id: Base64 connection_id.
:param str order_id: Base64 order_id.
:param str aes_key: Base64 AES key.
:return: Upload status code.
"""
self.dataset_upload = True
self.connect_to_socket()
if isinstance(directory,str):
if not os.path.isdir(directory):
raise Exception("Path not a directory!")
else:
raise Exception("Path must be a string!")
tasks = []
for dirpath, _, filenames in os.walk(directory):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
# print(file_path)
tasks.append(self.upload_file(file_path, connection_id, order_id, aes_key))
await asyncio.gather(*tasks)
print("FILES UPLOADED")
self.disconnect_from_socket()
return 201
“upload_file”所做的只是将文件内容转换为字节,将数据发送到套接字,并在返回之前等待“ack”消息。upload_file中没有会关闭连接的逻辑。
这是我处理套接字连接的 nodejs 服务器代码:
const setupSocketConnection = (io) => {
/* Socket connection */
io.on("connection", (socket) => {
console.log("A client connected");
// Handle file data
socket.on("file_data", async (payload) => {
const status = await handleSocketUpload(payload);
console.log(status);
socket.emit("ack", "0");
});
// Handle disconnection
socket.on("disconnect", () => {
console.log("Client disconnected");
});
});
};
handleSocketUpload() 几乎在数据传入后立即返回,因此这也不是问题的根源。
感谢您的帮助!
答: 暂无答案
评论