In Main Thread, I Create a WebSocket Connection Is OK, But When I Create In Sub Thread and Use domain URL, It Will Throw Exception(Use ipv4 URL Is OK).
Why Why Why??? It bothered me for a long time
When I Use Main Thread to create WebSocket Client Is Ok. like this:
import asyncio
import aiohttp
async def ws_client():
# WebSocket服务器的URL
url = 'ws://www.test.xyz' # faker domain
async with aiohttp.ClientSession() as session:
async with session.ws_connect(url) as ws:
print(f'success connect to {url}')
await ws.send_str('Hello, Server!')
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
print(f'message from server: {msg.data}')
elif msg.type == aiohttp.WSMsgType.ERROR:
print('occor a error')
break
print('close WebSocket')
if __name__ == "__main__":
asyncio.run(ws_client())
Like that Is Run Successfully
but When It run It in Sub Thread It will occor a error.
import asyncio
import aiohttp
import threading
import socket
class MyThread(threading.Thread):
def run(self) -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(ws_client())
async def ws_client():
""" Like Next Demo """
pass
if __name__ == "__main__":
t = MyThread()
t.start()
It throw Exception like this:
RuntimeError (note: full exception trace is shown but execution is paused at: ws_client)
can't register atexit after shutdown
File "H:sy_toolpy_websocket_clientsrctesttest_2.py", line 20, in ws_client (Current frame)
async with session.ws_connect(url) as ws:
File "H:sy_toolpy_websocket_clientsrctesttest_2.py", line 11, in run
asyncio.run(ws_client())
RuntimeError: can't register atexit after shutdown
But when i use ipv4 to replace domian url , It Run Successfuly, emmm…..
In Main Thread, I Create a WebSocket Connection Is OK, But When I Create In Sub Thread and Use domain URL, It Will Throw Exception(Use ipv4 URL Is OK).
Why Why Why??? It bothered me for a long time
I Use Python Version Is 3.10.10
被强煎的双黄蛋 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.