I'm building a Websocket server application in python 3. I'm using this implementation: https://websockets.readthedocs.io/
Basically I want to launch the server and client in the same process using different threads.
Here is my code. The server seems to start but the client does not connect.
What am I doing wrong ?
Guillaume
import asyncio
import websockets
import socket
from threading import Thread
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
# Get host and port from config file
server_host = socket.gethostname()
server_port = 8081 # random.randint(10000, 60000)
print('server_host: ' + server_host)
# start a new event loop
new_loop = asyncio.new_event_loop()
t = Thread(target=start_loop, args=(new_loop,))
t.start()
start_server = websockets.serve(hello, server_host, server_port, loop=new_loop)
print("Server launched")
async def hello():
uri = "ws://{}:{}".format(server_host, server_port)
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
await websocket.send(name)
print(f"> {name}")
greeting = await websocket.recv()
print(f"< {greeting}")
asyncio.get_event_loop().run_until_complete(hello())