I am running into this problem where the websocket will not close after I run an asynchronous function that asks for input ( i think its interrupting the main event loop or something).This code is just a recreation of the same problem that I ran into in my actual project where the “second function” actually runs a textual application but after i quit the app i cant get the connection to close. For some reason when I get to the “await websocket.close()” line it pauses and then times out without closing it.
import asyncio
import websockets
async def connect_and_send(ip, port):
uri = f"ws://{ip}:{port}"
websocket = await websockets.connect(uri)
# Send a message (optional)
await websocket.send(r"C:VolgisticsVlogger;Boi.txt;;None")
print("Message sent.")
# Call the second function
await second_function(websocket)
# Close the connection
print("Closing the connection...")
await websocket.close()
async def second_function(websocket):
# Perform some operations or send additional messages
input("Press Enter to send additional message...")
if input:
await websocket.send(r"C:VolgisticsVlogger;Boi.txt;second;None")
print("Additional message sent.")
# You can add more operations or logic here
# Replace with your desired IP and port
ip = "192.168.3.181"
port = 8888
asyncio.run(connect_and_send(ip, port))
I’ve tried various approaches, such as using threading.Thread to run the asynchronous function in a separate thread, creating a new event loop within the thread, and awaiting the websocket.close() operation in the main event loop. However, I’m still unable to close the WebSocket connection properly after the asynchronous function completes.
My goal is to ensure that the WebSocket connection is closed cleanly after the asynchronous function finishes executing. This is a simplified example, but I’m facing a similar issue in my actual project.
Can someone please help me understand what I’m doing wrong and provide a solution to properly close the WebSocket connection in this scenario?
Gabriel Vanderklok is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.