diff --git a/src/websockets/sync/server.py b/src/websockets/sync/server.py index a070edf18..b8eff9c5a 100644 --- a/src/websockets/sync/server.py +++ b/src/websockets/sync/server.py @@ -263,6 +263,14 @@ def __exit__( ) -> None: self.shutdown() +def is_websocket(connection): + """ + return True if the connection is a websocket + + """ + upgrade_header = connection.__dict__.get('request').headers.get('Upgrade', '') + connection_header = connection.__dict__.get('request').headers.get('Connection', '') + return upgrade_header.lower() == 'websocket' and connection_header.lower() == 'upgrade' def serve( handler: Callable[[ServerConnection], None], @@ -508,7 +516,8 @@ def protocol_select_subprotocol( return try: - handler(connection) + if is_websocket(connection): + handler(connection) except Exception: protocol.logger.error("connection handler failed", exc_info=True) connection.close(CloseCode.INTERNAL_ERROR)