1

I have the following class for opening my websockets:

import os
import asyncio  
import websockets
import threading

class Server:

    def get_port(self):
        return os.getenv('WS_PORT', '9002')

    def get_host(self):
        return os.getenv('WS_HOST', 'localhost')

    def shutdown(self):
        self.loop.call_soon_threadsafe(self.loop.stop)

    def start(self):
        return websockets.serve(self.handler, self.get_host(), self.get_port())

Followed by some async handling methods for incoming messages. The loop function for getting the messages runs in its own thread, just for information.

I am able to terminate the program, however I was not able to close the sockets properly, cause it causes the following error on the restart of the script

OSError: [Errno 10048] error while attempting to bind on address ('127.0.0.1', 9002):

Since the port is already in use. Usually I would use some .close() function, however the websocket package does not provide such function, so I am wondering if I can get this done with the os package or the websocket package?

matisetorm
  • 857
  • 8
  • 21
Kev1n91
  • 3,553
  • 8
  • 46
  • 96

1 Answers1

2

The proper shutdown process is discussed here. The basic idea is to use the serve() method as an async context manager.

async with websockets.serve(echo, 'localhost', 9002):
    await stop

For example, stop can be a Future. The await "returns" when you call stop.set_result(). The context manager will then shutdown the server gracefully.

Usually, you would use a signal handler to trigger the stop condition (an example is also included in the docs).

You also might get the error, when the socket is not opened with socket.SO_REUSEADDR by the framework. See this question for details.

code_onkel
  • 2,759
  • 1
  • 16
  • 31
  • Thank you, your mentioned solution did not work for me, since I am on windows. However your provided link showed a solution, which worked, thank you – Kev1n91 Feb 16 '18 at 12:55