Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I receive "WebSocket connection is closed: code = 1000 (OK), no reason"

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

like image 477
shalakhin Avatar asked Jan 01 '18 19:01

shalakhin


1 Answers

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()
like image 119
Yohannes Avatar answered Oct 19 '22 10:10

Yohannes