I have the following server:
import os
import asyncio
import websockets
class Server:
    def get_port(self):
        return os.getenv('WS_PORT', '8765')
    def get_host(self):
        return os.getenv('WS_HOST', 'localhost')
    def start(self):
        return websockets.serve(self.handler, self.get_host(), self.get_port())
    async def handler(self, websocket, path):
        while True:
            async for message in websocket:
                await websocket.send(message)
and the client:
import asyncio
import websockets
async def msg():
    async with websockets.connect('ws://localhost:8765') as websocket:
        await websocket.send('test message')
asyncio.get_event_loop().run_until_complete(msg())
When I execute asyncio.get_event_loop().run_until_complete(msg()) I receive the following error:
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1000 (OK), no reason
Also app.py code:
#!/usr/bin/env python3.6
import asyncio
from server import Server
if __name__ == '__main__':
    ws = Server()
    asyncio.get_event_loop().run_until_complete(ws.start())
    asyncio.get_event_loop().run_forever()
P.S. Added while True to handler as suggested in the comment below. But I still receive that error
You aren't starting the server
server.py:
import os
import asyncio
import websockets
class Server:
    def get_port(self):
        return os.getenv('WS_PORT', '8765')
    def get_host(self):
        return os.getenv('WS_HOST', 'localhost')
    def start(self):
        return websockets.serve(self.handler, self.get_host(), self.get_port())
    async def handler(self, websocket, path):
      async for message in websocket:
        print('server received :', message)
        await websocket.send(message)
if __name__ == '__main__':
  ws = Server()
  asyncio.get_event_loop().run_until_complete(ws.start())
  asyncio.get_event_loop().run_forever()
client.py
#!/usr/bin/env python3.6
import asyncio
import websockets
async def msg():
    async with websockets.connect('ws://localhost:8765') as websocket:
        await websocket.send('test message')
        msg = await websocket.recv()
        print(msg)
if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(msg())
    asyncio.get_event_loop().run_forever()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With