【问题标题】:Python / Websockets : Opening file in socket callback reset the connectionPython / Websockets:在套接字回调中打开文件重置连接
【发布时间】: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


【解决方案1】:

不确定这是否有帮助,但您可以使用日志库创建记录器:https://docs.python.org/3/howto/logging.html

【讨论】:

  • 这是一个很好的解决我的问题的方法,即使它不能解释问题。谢谢;)
  • 我还有一个问题:执行期间访问日志文件,重置套接字。
  • 尝试通过编写另一个包含的程序以只读模式访问文件。 f = open("logfile", 'r') print(f.readlines())
  • 还在 async def handler(websocket) 之前使用 'w+' 创建日志文件,然后在 async def handler(websocket) 函数中使用 'a+' 附加到它。
  • 我试过了,还是不行。在第二次 logging.info 调用中,我得到了与打开经典文件时相同的行为
【解决方案2】:

我了解我的问题。奇怪的行为来自 Windows WSL。我在真正的 Linux 上测试了相同的代码,没有问题。目前,我在 Windows WSL 上没有任何解决方案。

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 2013-04-13
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多