【发布时间】:2022-01-22 09:57:51
【问题描述】:
我正在使用 python 服务器创建一个网站。我正在使用 websockets 库。
我想添加日志文件以在网站运行期间监控我的网站活动。
但是如果我在套接字回调中打开一个文件,套接字连接总是在打开时重置。
import asyncio
import websockets
async def handler(websocket):
while True:
try:
testFile = open("log", "w") # This line reset socket connection
testFile.write('anything')
testFile.close()
message = await websocket.recv()
await websocket.send('{"cmd" : "ERROR", "msg" : "This is a test"}')
except websockets.ConnectionClosedOK:
break
async def main():
async with websockets.serve(handler, "", 50000):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
编辑:如果我删除 try except 块,我收到以下错误:
connection handler failed
Traceback (most recent call last):
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 231, in handler
await self.ws_handler(self)
File "server2.py", line 52, in handler
message = await websocket.recv()
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 552, in recv
await self.ensure_open()
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 929, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1001 (going away); then sent 1001 (going away)
(我也尝试过使用另一个套接字库(simple_websocket_server),问题是一样的)
有没有办法避免这种行为?如果没有,是否有另一种方法可以在服务器执行期间获取日志?
【问题讨论】:
-
无法复制。但是在我的测试中,当前工作目录是进程可写的,并且
log文件被成功创建。您可以使用可写文件的完整路径并再次测试吗? -
“可写的完整路径”是什么意思?绝对路径?在我的情况下,文件也被正确写入。但是我的套接字连接被重置(浏览器页面被刷新)。
标签: python python-3.x websocket