A simple web server used for running Socket.IO servers in tests. :param sio: a Socket.IO server instance. Note 1: This class is not production-ready and is intended for testing. Note 2: This class only supports the "threading" async_mode, with WebSocket support provided by the simp
| 7 | |
| 8 | |
| 9 | class SocketIOWebServer: |
| 10 | """A simple web server used for running Socket.IO servers in tests. |
| 11 | |
| 12 | :param sio: a Socket.IO server instance. |
| 13 | |
| 14 | Note 1: This class is not production-ready and is intended for testing. |
| 15 | Note 2: This class only supports the "threading" async_mode, with WebSocket |
| 16 | support provided by the simple-websocket package. |
| 17 | """ |
| 18 | def __init__(self, sio): |
| 19 | if sio.async_mode != 'threading': |
| 20 | raise ValueError('The async_mode must be "threading"') |
| 21 | |
| 22 | def http_app(environ, start_response): |
| 23 | start_response('200 OK', [('Content-Type', 'text/plain')]) |
| 24 | return [b'OK'] |
| 25 | |
| 26 | self.sio = sio |
| 27 | self.app = socketio.WSGIApp(sio, http_app) |
| 28 | self.httpd = None |
| 29 | self.thread = None |
| 30 | |
| 31 | def start(self, port=8900): |
| 32 | """Start the web server. |
| 33 | |
| 34 | :param port: the port to listen on. Defaults to 8900. |
| 35 | |
| 36 | The server is started in a background thread. |
| 37 | """ |
| 38 | class ThreadingWSGIServer(ThreadingMixIn, WSGIServer): |
| 39 | pass |
| 40 | |
| 41 | class WebSocketRequestHandler(WSGIRequestHandler): |
| 42 | def get_environ(self): |
| 43 | env = super().get_environ() |
| 44 | |
| 45 | # pass the raw socket to the WSGI app so that it can be used |
| 46 | # by WebSocket connections (hack copied from gunicorn) |
| 47 | env['gunicorn.socket'] = self.connection |
| 48 | return env |
| 49 | |
| 50 | self.httpd = make_server('localhost', port, self._app_wrapper, |
| 51 | ThreadingWSGIServer, WebSocketRequestHandler) |
| 52 | self.thread = threading.Thread(target=self.httpd.serve_forever) |
| 53 | self.thread.start() |
| 54 | |
| 55 | # wait for the server to start |
| 56 | while True: |
| 57 | try: |
| 58 | r = requests.get(f'http://localhost:{port}/') |
| 59 | r.raise_for_status() |
| 60 | if r.text == 'OK': |
| 61 | break |
| 62 | except: |
| 63 | time.sleep(0.1) |
| 64 | |
| 65 | def stop(self): |
| 66 | """Stop the web server.""" |