{
    "file_diffs": [
        {
            "old_file_content": "import asyncio\nimport functools\nimport traceback\nimport typing\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado import gen\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.locks import Event\nfrom tornado.log import gen_log, app_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket  # noqa: F401\n    from tornado.util import _websocket_mask_python\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import (\n    WebSocketHandler,\n    websocket_connect,\n    WebSocketError,\n    WebSocketClosedError,\n)\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None  # type: ignore\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for tests to see the close code and reason on the\n    server side.\n\n    \"\"\"\n\n    def initialize(self, close_future=None, compression_options=None):\n        self.close_future = close_future\n        self.compression_options = compression_options\n\n    def get_compression_options(self):\n        return self.compression_options\n\n    def on_close(self):\n        if self.close_future is not None:\n            self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def on_message(self, message):\n        try:\n            yield self.write_message(message, isinstance(message, bytes))\n        except asyncio.CancelledError:\n            pass\n        except WebSocketClosedError:\n            pass\n\n\nclass ErrorInOnMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        1 / 0\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        methods_to_test = [\n            functools.partial(self.write, \"This should not work\"),\n            functools.partial(self.redirect, \"http://localhost/elsewhere\"),\n            functools.partial(self.set_header, \"X-Test\", \"\"),\n            functools.partial(self.set_cookie, \"Chocolate\", \"Chip\"),\n            functools.partial(self.set_status, 503),\n            self.flush,\n            self.finish,\n        ]\n        for method in methods_to_test:\n            try:\n                # In a websocket context, many RequestHandler methods\n                # raise RuntimeErrors.\n                method()  # type: ignore\n                raise Exception(\"did not get expected exception\")\n            except RuntimeError:\n                pass\n        self.write_message(self.request.headers.get(\"X-Test\", \"\"))\n\n\nclass HeaderEchoHandler(TestWebSocketHandler):\n    def set_default_headers(self):\n        self.set_header(\"X-Extra-Response-Header\", \"Extra-Response-Value\")\n\n    def prepare(self):\n        for k, v in self.request.headers.get_all():\n            if k.lower().startswith(\"x-test\"):\n                self.set_header(k, v)\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write(\"ok\")\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.on_close_called = False\n        self.close(1001, \"goodbye\")\n\n\nclass AsyncPrepareHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n\n    def on_message(self, message):\n        self.write_message(message)\n\n\nclass PathArgsHandler(TestWebSocketHandler):\n    def open(self, arg):\n        self.write_message(arg)\n\n\nclass CoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    @gen.coroutine\n    def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        yield gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass RenderMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(self.render_string(\"message.html\", message=message))\n\n\nclass SubprotocolHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.select_subprotocol_called = False\n\n    def select_subprotocol(self, subprotocols):\n        if self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol called twice\")\n        self.select_subprotocol_called = True\n        if \"goodproto\" in subprotocols:\n            return \"goodproto\"\n        return None\n\n    def open(self):\n        if not self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol not called\")\n        self.write_message(\"subprotocol=%s\" % self.selected_subprotocol)\n\n\nclass OpenCoroutineHandler(TestWebSocketHandler):\n    def initialize(self, test, **kwargs):\n        super().initialize(**kwargs)\n        self.test = test\n        self.open_finished = False\n\n    @gen.coroutine\n    def open(self):\n        yield self.test.message_sent.wait()\n        yield gen.sleep(0.010)\n        self.open_finished = True\n\n    def on_message(self, message):\n        if not self.open_finished:\n            raise Exception(\"on_message called before open finished\")\n        self.write_message(\"ok\")\n\n\nclass ErrorInOpenHandler(TestWebSocketHandler):\n    def open(self):\n        raise Exception(\"boom\")\n\n\nclass ErrorInAsyncOpenHandler(TestWebSocketHandler):\n    async def open(self):\n        await asyncio.sleep(0)\n        raise Exception(\"boom\")\n\n\nclass NoDelayHandler(TestWebSocketHandler):\n    def open(self):\n        self.set_nodelay(True)\n        self.write_message(\"hello\")\n\n\nclass WebSocketBaseTestCase(AsyncHTTPTestCase):\n    @gen.coroutine\n    def ws_connect(self, path, **kwargs):\n        ws = yield websocket_connect(\n            \"ws://127.0.0.1:%d%s\" % (self.get_http_port(), path), **kwargs\n        )\n        raise gen.Return(ws)\n\n\nclass WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n\nclass NativeCoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    async def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        await gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass WebSocketNativeCoroutineTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/native\", NativeCoroutineOnMessageHandler)])\n\n    @gen_test\n    def test_native_coroutine(self):\n        ws = yield self.ws_connect(\"/native\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n\nclass CompressionTestMixin(object):\n    MESSAGE = \"Hello world. Testing 123 123\"\n\n    def get_app(self):\n        class LimitedHandler(TestWebSocketHandler):\n            @property\n            def max_message_size(self):\n                return 1024\n\n            def on_message(self, message):\n                self.write_message(str(len(message)))\n\n        return Application(\n            [\n                (\n                    \"/echo\",\n                    EchoHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n                (\n                    \"/limited\",\n                    LimitedHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n            ]\n        )\n\n    def get_server_compression_options(self):\n        return None\n\n    def get_client_compression_options(self):\n        return None\n\n    def verify_wire_bytes(self, bytes_in: int, bytes_out: int) -> None:\n        raise NotImplementedError()\n\n    @gen_test\n    def test_message_sizes(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/echo\", compression_options=self.get_client_compression_options()\n        )\n        # Send the same message three times so we can measure the\n        # effect of the context_takeover options.\n        for i in range(3):\n            ws.write_message(self.MESSAGE)\n            response = yield ws.read_message()\n            self.assertEqual(response, self.MESSAGE)\n        self.assertEqual(ws.protocol._message_bytes_out, len(self.MESSAGE) * 3)\n        self.assertEqual(ws.protocol._message_bytes_in, len(self.MESSAGE) * 3)\n        self.verify_wire_bytes(ws.protocol._wire_bytes_in, ws.protocol._wire_bytes_out)\n\n    @gen_test\n    def test_size_limit(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/limited\", compression_options=self.get_client_compression_options()\n        )\n        # Small messages pass through.\n        ws.write_message(\"a\" * 128)\n        response = yield ws.read_message()\n        self.assertEqual(response, \"128\")\n        # This message is too big after decompression, but it compresses\n        # down to a size that will pass the initial checks.\n        ws.write_message(\"a\" * 2048)\n        response = yield ws.read_message()\n        self.assertIsNone(response)\n\n\nclass UncompressedTestMixin(CompressionTestMixin):\n    \"\"\"Specialization of CompressionTestMixin when we expect no compression.\"\"\"\n\n    def verify_wire_bytes(self: typing.Any, bytes_in, bytes_out):\n        # Bytes out includes the 4-byte mask key per message.\n        self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertEqual(bytes_in, 3 * (len(self.MESSAGE) + 2))\n\n\nclass NoCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    pass\n\n\n# If only one side tries to compress, the extension is not negotiated.\nclass ServerOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n\nclass ClientOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_client_compression_options(self):\n        return {}\n\n\nclass DefaultCompressionTest(CompressionTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n    def get_client_compression_options(self):\n        return {}\n\n    def verify_wire_bytes(self, bytes_in, bytes_out):\n        self.assertLess(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertLess(bytes_in, 3 * (len(self.MESSAGE) + 2))\n        # Bytes out includes the 4 bytes mask key per message.\n        self.assertEqual(bytes_out, bytes_in + 12)\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def mask(self, mask: bytes, data: bytes) -> bytes:\n        raise NotImplementedError()\n\n    def test_mask(self: typing.Any):\n        self.assertEqual(self.mask(b\"abcd\", b\"\"), b\"\")\n        self.assertEqual(self.mask(b\"abcd\", b\"b\"), b\"\\x03\")\n        self.assertEqual(self.mask(b\"abcd\", b\"54321\"), b\"TVPVP\")\n        self.assertEqual(self.mask(b\"ZXCV\", b\"98765432\"), b\"c`t`olpd\")\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(\n            self.mask(b\"\\x00\\x01\\x02\\x03\", b\"\\xff\\xfb\\xfd\\xfc\\xfe\\xfa\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfe\\xfb\",\n        )\n        self.assertEqual(\n            self.mask(b\"\\xff\\xfb\\xfd\\xfc\", b\"\\x00\\x01\\x02\\x03\\x04\\x05\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfb\\xfe\",\n        )\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\n\n\nclass ServerPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_pong(self, data):\n                self.write_message(\"got pong\")\n\n        return Application([(\"/\", PingHandler)], websocket_ping_interval=0.01)\n\n    @gen_test\n    def test_server_ping(self):\n        ws = yield self.ws_connect(\"/\")\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got pong\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ClientPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(\"got ping\")\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_client_ping(self):\n        ws = yield self.ws_connect(\"/\", ping_interval=0.01)\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got ping\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ManualPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(data, binary=isinstance(data, bytes))\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_manual_ping(self):\n        ws = yield self.ws_connect(\"/\")\n\n        self.assertRaises(ValueError, ws.ping, \"a\" * 126)\n\n        ws.ping(\"hello\")\n        resp = yield ws.read_message()\n        # on_ping always sees bytes.\n        self.assertEqual(resp, b\"hello\")\n\n        ws.ping(b\"binary hello\")\n        resp = yield ws.read_message()\n        self.assertEqual(resp, b\"binary hello\")\n\n\nclass MaxMessageSizeTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/\", EchoHandler)], websocket_max_message_size=1024)\n\n    @gen_test\n    def test_large_message(self):\n        ws = yield self.ws_connect(\"/\")\n\n        # Write a message that is allowed.\n        msg = \"a\" * 1024\n        ws.write_message(msg)\n        resp = yield ws.read_message()\n        self.assertEqual(resp, msg)\n\n        # Write a message that is too large.\n        ws.write_message(msg + \"b\")\n        resp = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(resp, None)\n        self.assertEqual(ws.close_code, 1009)\n        self.assertEqual(ws.close_reason, \"message too big\")\n        # TODO: Needs tests of messages split over multiple\n        # continuation frames.\n",
            "new_file_content": "import asyncio\nimport functools\nimport traceback\nimport typing\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado import gen\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.locks import Event\nfrom tornado.log import gen_log, app_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket  # noqa: F401\n    from tornado.util import _websocket_mask_python\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import (\n    WebSocketHandler,\n    websocket_connect,\n    WebSocketError,\n    WebSocketClosedError,\n)\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None  # type: ignore\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for tests to see the close code and reason on the\n    server side.\n\n    \"\"\"\n\n    def initialize(self, close_future=None, compression_options=None):\n        self.close_future = close_future\n        self.compression_options = compression_options\n\n    def get_compression_options(self):\n        return self.compression_options\n\n    def on_close(self):\n        if self.close_future is not None:\n            self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def on_message(self, message):\n        try:\n            yield self.write_message(message, isinstance(message, bytes))\n        except asyncio.CancelledError:\n            pass\n        except WebSocketClosedError:\n            pass\n\n\nclass ErrorInOnMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        1 / 0\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        methods_to_test = [\n            functools.partial(self.write, \"This should not work\"),\n            functools.partial(self.redirect, \"http://localhost/elsewhere\"),\n            functools.partial(self.set_header, \"X-Test\", \"\"),\n            functools.partial(self.set_cookie, \"Chocolate\", \"Chip\"),\n            functools.partial(self.set_status, 503),\n            self.flush,\n            self.finish,\n        ]\n        for method in methods_to_test:\n            try:\n                # In a websocket context, many RequestHandler methods\n                # raise RuntimeErrors.\n                method()  # type: ignore\n                raise Exception(\"did not get expected exception\")\n            except RuntimeError:\n                pass\n        self.write_message(self.request.headers.get(\"X-Test\", \"\"))\n\n\nclass HeaderEchoHandler(TestWebSocketHandler):\n    def set_default_headers(self):\n        self.set_header(\"X-Extra-Response-Header\", \"Extra-Response-Value\")\n\n    def prepare(self):\n        for k, v in self.request.headers.get_all():\n            if k.lower().startswith(\"x-test\"):\n                self.set_header(k, v)\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write(\"ok\")\n\n\nclass RedirectHandler(RequestHandler):\n    def get(self):\n        self.redirect(\"/echo\")\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.on_close_called = False\n        self.close(1001, \"goodbye\")\n\n\nclass AsyncPrepareHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n\n    def on_message(self, message):\n        self.write_message(message)\n\n\nclass PathArgsHandler(TestWebSocketHandler):\n    def open(self, arg):\n        self.write_message(arg)\n\n\nclass CoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    @gen.coroutine\n    def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        yield gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass RenderMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(self.render_string(\"message.html\", message=message))\n\n\nclass SubprotocolHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.select_subprotocol_called = False\n\n    def select_subprotocol(self, subprotocols):\n        if self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol called twice\")\n        self.select_subprotocol_called = True\n        if \"goodproto\" in subprotocols:\n            return \"goodproto\"\n        return None\n\n    def open(self):\n        if not self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol not called\")\n        self.write_message(\"subprotocol=%s\" % self.selected_subprotocol)\n\n\nclass OpenCoroutineHandler(TestWebSocketHandler):\n    def initialize(self, test, **kwargs):\n        super().initialize(**kwargs)\n        self.test = test\n        self.open_finished = False\n\n    @gen.coroutine\n    def open(self):\n        yield self.test.message_sent.wait()\n        yield gen.sleep(0.010)\n        self.open_finished = True\n\n    def on_message(self, message):\n        if not self.open_finished:\n            raise Exception(\"on_message called before open finished\")\n        self.write_message(\"ok\")\n\n\nclass ErrorInOpenHandler(TestWebSocketHandler):\n    def open(self):\n        raise Exception(\"boom\")\n\n\nclass ErrorInAsyncOpenHandler(TestWebSocketHandler):\n    async def open(self):\n        await asyncio.sleep(0)\n        raise Exception(\"boom\")\n\n\nclass NoDelayHandler(TestWebSocketHandler):\n    def open(self):\n        self.set_nodelay(True)\n        self.write_message(\"hello\")\n\n\nclass WebSocketBaseTestCase(AsyncHTTPTestCase):\n    @gen.coroutine\n    def ws_connect(self, path, **kwargs):\n        ws = yield websocket_connect(\n            \"ws://127.0.0.1:%d%s\" % (self.get_http_port(), path), **kwargs\n        )\n        raise gen.Return(ws)\n\n\nclass WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n\nclass NativeCoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    async def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        await gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass WebSocketNativeCoroutineTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/native\", NativeCoroutineOnMessageHandler)])\n\n    @gen_test\n    def test_native_coroutine(self):\n        ws = yield self.ws_connect(\"/native\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n\nclass CompressionTestMixin(object):\n    MESSAGE = \"Hello world. Testing 123 123\"\n\n    def get_app(self):\n        class LimitedHandler(TestWebSocketHandler):\n            @property\n            def max_message_size(self):\n                return 1024\n\n            def on_message(self, message):\n                self.write_message(str(len(message)))\n\n        return Application(\n            [\n                (\n                    \"/echo\",\n                    EchoHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n                (\n                    \"/limited\",\n                    LimitedHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n            ]\n        )\n\n    def get_server_compression_options(self):\n        return None\n\n    def get_client_compression_options(self):\n        return None\n\n    def verify_wire_bytes(self, bytes_in: int, bytes_out: int) -> None:\n        raise NotImplementedError()\n\n    @gen_test\n    def test_message_sizes(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/echo\", compression_options=self.get_client_compression_options()\n        )\n        # Send the same message three times so we can measure the\n        # effect of the context_takeover options.\n        for i in range(3):\n            ws.write_message(self.MESSAGE)\n            response = yield ws.read_message()\n            self.assertEqual(response, self.MESSAGE)\n        self.assertEqual(ws.protocol._message_bytes_out, len(self.MESSAGE) * 3)\n        self.assertEqual(ws.protocol._message_bytes_in, len(self.MESSAGE) * 3)\n        self.verify_wire_bytes(ws.protocol._wire_bytes_in, ws.protocol._wire_bytes_out)\n\n    @gen_test\n    def test_size_limit(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/limited\", compression_options=self.get_client_compression_options()\n        )\n        # Small messages pass through.\n        ws.write_message(\"a\" * 128)\n        response = yield ws.read_message()\n        self.assertEqual(response, \"128\")\n        # This message is too big after decompression, but it compresses\n        # down to a size that will pass the initial checks.\n        ws.write_message(\"a\" * 2048)\n        response = yield ws.read_message()\n        self.assertIsNone(response)\n\n\nclass UncompressedTestMixin(CompressionTestMixin):\n    \"\"\"Specialization of CompressionTestMixin when we expect no compression.\"\"\"\n\n    def verify_wire_bytes(self: typing.Any, bytes_in, bytes_out):\n        # Bytes out includes the 4-byte mask key per message.\n        self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertEqual(bytes_in, 3 * (len(self.MESSAGE) + 2))\n\n\nclass NoCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    pass\n\n\n# If only one side tries to compress, the extension is not negotiated.\nclass ServerOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n\nclass ClientOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_client_compression_options(self):\n        return {}\n\n\nclass DefaultCompressionTest(CompressionTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n    def get_client_compression_options(self):\n        return {}\n\n    def verify_wire_bytes(self, bytes_in, bytes_out):\n        self.assertLess(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertLess(bytes_in, 3 * (len(self.MESSAGE) + 2))\n        # Bytes out includes the 4 bytes mask key per message.\n        self.assertEqual(bytes_out, bytes_in + 12)\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def mask(self, mask: bytes, data: bytes) -> bytes:\n        raise NotImplementedError()\n\n    def test_mask(self: typing.Any):\n        self.assertEqual(self.mask(b\"abcd\", b\"\"), b\"\")\n        self.assertEqual(self.mask(b\"abcd\", b\"b\"), b\"\\x03\")\n        self.assertEqual(self.mask(b\"abcd\", b\"54321\"), b\"TVPVP\")\n        self.assertEqual(self.mask(b\"ZXCV\", b\"98765432\"), b\"c`t`olpd\")\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(\n            self.mask(b\"\\x00\\x01\\x02\\x03\", b\"\\xff\\xfb\\xfd\\xfc\\xfe\\xfa\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfe\\xfb\",\n        )\n        self.assertEqual(\n            self.mask(b\"\\xff\\xfb\\xfd\\xfc\", b\"\\x00\\x01\\x02\\x03\\x04\\x05\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfb\\xfe\",\n        )\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\n\n\nclass ServerPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_pong(self, data):\n                self.write_message(\"got pong\")\n\n        return Application([(\"/\", PingHandler)], websocket_ping_interval=0.01)\n\n    @gen_test\n    def test_server_ping(self):\n        ws = yield self.ws_connect(\"/\")\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got pong\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ClientPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(\"got ping\")\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_client_ping(self):\n        ws = yield self.ws_connect(\"/\", ping_interval=0.01)\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got ping\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ManualPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(data, binary=isinstance(data, bytes))\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_manual_ping(self):\n        ws = yield self.ws_connect(\"/\")\n\n        self.assertRaises(ValueError, ws.ping, \"a\" * 126)\n\n        ws.ping(\"hello\")\n        resp = yield ws.read_message()\n        # on_ping always sees bytes.\n        self.assertEqual(resp, b\"hello\")\n\n        ws.ping(b\"binary hello\")\n        resp = yield ws.read_message()\n        self.assertEqual(resp, b\"binary hello\")\n\n\nclass MaxMessageSizeTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/\", EchoHandler)], websocket_max_message_size=1024)\n\n    @gen_test\n    def test_large_message(self):\n        ws = yield self.ws_connect(\"/\")\n\n        # Write a message that is allowed.\n        msg = \"a\" * 1024\n        ws.write_message(msg)\n        resp = yield ws.read_message()\n        self.assertEqual(resp, msg)\n\n        # Write a message that is too large.\n        ws.write_message(msg + \"b\")\n        resp = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(resp, None)\n        self.assertEqual(ws.close_code, 1009)\n        self.assertEqual(ws.close_reason, \"message too big\")\n        # TODO: Needs tests of messages split over multiple\n        # continuation frames.\n",
            "header": {
                "file": {
                    "path": "tornado/test/websocket_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "766b14b8",
                "new_commit_hash": "befe06dd",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/websocket_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/websocket_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 111,
                            "length": 6
                        },
                        "new_range": {
                            "start": 111,
                            "length": 11
                        },
                        "section": "class NonWebSocketHandler(RequestHandler):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.write(\"ok\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class RedirectHandler(RequestHandler):",
                                "type": "added"
                            },
                            {
                                "content": "    def get(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.redirect(\"/echo\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "class CloseReasonHandler(TestWebSocketHandler):",
                                "type": "context"
                            },
                            {
                                "content": "    def open(self):",
                                "type": "context"
                            },
                            {
                                "content": "        self.on_close_called = False",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "class",
                            "name": "RedirectHandler",
                            "content": "class RedirectHandler(RequestHandler):\n    def get(self):\n        self.redirect(\"/echo\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 114,
                            "end_lineno": 116,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "method",
                            "name": "RedirectHandler.get",
                            "content": "class RedirectHandler(RequestHandler):\n    def get(self):\n        self.redirect(\"/echo\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 115,
                            "end_lineno": 116,
                            "parent": {
                                "file_name": "tornado/test/websocket_test.py",
                                "type": "class",
                                "name": "RedirectHandler",
                                "content": "class RedirectHandler(RequestHandler):\n    def get(self):\n        self.redirect(\"/echo\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 114,
                                "end_lineno": 116,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 221,
                            "length": 6
                        },
                        "new_range": {
                            "start": 226,
                            "length": 7
                        },
                        "section": "class WebSocketTest(WebSocketBaseTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "            [",
                                "type": "context"
                            },
                            {
                                "content": "                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),",
                                "type": "context"
                            },
                            {
                                "content": "                (\"/non_ws\", NonWebSocketHandler),",
                                "type": "context"
                            },
                            {
                                "content": "                (\"/redirect\", RedirectHandler),",
                                "type": "added"
                            },
                            {
                                "content": "                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),",
                                "type": "context"
                            },
                            {
                                "content": "                (",
                                "type": "context"
                            },
                            {
                                "content": "                    \"/header_echo\",",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "class",
                            "name": "WebSocketTest",
                            "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 222,
                            "end_lineno": 588,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "method",
                            "name": "WebSocketTest.get_app",
                            "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 223,
                            "end_lineno": 277,
                            "parent": {
                                "file_name": "tornado/test/websocket_test.py",
                                "type": "class",
                                "name": "WebSocketTest",
                                "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 222,
                                "end_lineno": 588,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 365,
                            "length": 6
                        },
                        "new_range": {
                            "start": 371,
                            "length": 11
                        },
                        "section": "class WebSocketTest(WebSocketBaseTestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        with self.assertRaises(WebSocketError):",
                                "type": "context"
                            },
                            {
                                "content": "            yield self.ws_connect(\"/non_ws\")",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "added"
                            },
                            {
                                "content": "    def test_websocket_http_redirect(self):",
                                "type": "added"
                            },
                            {
                                "content": "        with self.assertRaises(HTTPError):",
                                "type": "added"
                            },
                            {
                                "content": "            yield self.ws_connect(\"/redirect\")",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    @gen_test",
                                "type": "context"
                            },
                            {
                                "content": "    def test_websocket_network_fail(self):",
                                "type": "context"
                            },
                            {
                                "content": "        sock, port = bind_unused_port()",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "class",
                            "name": "WebSocketTest",
                            "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 222,
                            "end_lineno": 588,
                            "parent": null
                        }
                    ],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/websocket_test.py",
                            "type": "method",
                            "name": "WebSocketTest.test_websocket_http_redirect",
                            "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 375,
                            "end_lineno": 377,
                            "parent": {
                                "file_name": "tornado/test/websocket_test.py",
                                "type": "class",
                                "name": "WebSocketTest",
                                "content": "class WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 222,
                                "end_lineno": 588,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "\"\"\"Implementation of the WebSocket protocol.\n\n`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional\ncommunication between the browser and server.\n\nWebSockets are supported in the current versions of all major browsers,\nalthough older versions that do not support WebSockets are still in use\n(refer to http://caniuse.com/websockets for details).\n\nThis module implements the final version of the WebSocket protocol as\ndefined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_.  Certain\nbrowser versions (notably Safari 5.x) implemented an earlier draft of\nthe protocol (known as \"draft 76\") and are not compatible with this module.\n\n.. versionchanged:: 4.0\n   Removed support for the draft 76 protocol version.\n\"\"\"\n\nimport abc\nimport asyncio\nimport base64\nimport hashlib\nimport os\nimport sys\nimport struct\nimport tornado.escape\nimport tornado.web\nfrom urllib.parse import urlparse\nimport zlib\n\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.escape import utf8, native_str, to_unicode\nfrom tornado import gen, httpclient, httputil\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.log import gen_log, app_log\nfrom tornado import simple_httpclient\nfrom tornado.queues import Queue\nfrom tornado.tcpclient import TCPClient\nfrom tornado.util import _websocket_mask\n\nfrom typing import (\n    TYPE_CHECKING,\n    cast,\n    Any,\n    Optional,\n    Dict,\n    Union,\n    List,\n    Awaitable,\n    Callable,\n    Tuple,\n    Type,\n)\nfrom types import TracebackType\n\nif TYPE_CHECKING:\n    from typing_extensions import Protocol\n\n    # The zlib compressor types aren't actually exposed anywhere\n    # publicly, so declare protocols for the portions we use.\n    class _Compressor(Protocol):\n        def compress(self, data: bytes) -> bytes:\n            pass\n\n        def flush(self, mode: int) -> bytes:\n            pass\n\n    class _Decompressor(Protocol):\n        unconsumed_tail = b\"\"  # type: bytes\n\n        def decompress(self, data: bytes, max_length: int) -> bytes:\n            pass\n\n    class _WebSocketDelegate(Protocol):\n        # The common base interface implemented by WebSocketHandler on\n        # the server side and WebSocketClientConnection on the client\n        # side.\n        def on_ws_connection_close(\n            self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n        ) -> None:\n            pass\n\n        def on_message(self, message: Union[str, bytes]) -> Optional[\"Awaitable[None]\"]:\n            pass\n\n        def on_ping(self, data: bytes) -> None:\n            pass\n\n        def on_pong(self, data: bytes) -> None:\n            pass\n\n        def log_exception(\n            self,\n            typ: Optional[Type[BaseException]],\n            value: Optional[BaseException],\n            tb: Optional[TracebackType],\n        ) -> None:\n            pass\n\n\n_default_max_message_size = 10 * 1024 * 1024\n\n\nclass WebSocketError(Exception):\n    pass\n\n\nclass WebSocketClosedError(WebSocketError):\n    \"\"\"Raised by operations on a closed connection.\n\n    .. versionadded:: 3.2\n    \"\"\"\n\n    pass\n\n\nclass _DecompressTooLargeError(Exception):\n    pass\n\n\nclass _WebSocketParams(object):\n    def __init__(\n        self,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self.ping_interval = ping_interval\n        self.ping_timeout = ping_timeout\n        self.max_message_size = max_message_size\n        self.compression_options = compression_options\n\n\nclass WebSocketHandler(tornado.web.RequestHandler):\n    \"\"\"Subclass this class to create a basic WebSocket handler.\n\n    Override `on_message` to handle incoming messages, and use\n    `write_message` to send messages to the client. You can also\n    override `open` and `on_close` to handle opened and closed\n    connections.\n\n    Custom upgrade response headers can be sent by overriding\n    `~tornado.web.RequestHandler.set_default_headers` or\n    `~tornado.web.RequestHandler.prepare`.\n\n    See http://dev.w3.org/html5/websockets/ for details on the\n    JavaScript interface.  The protocol is specified at\n    http://tools.ietf.org/html/rfc6455.\n\n    Here is an example WebSocket handler that echos back all received messages\n    back to the client:\n\n    .. testcode::\n\n      class EchoWebSocket(tornado.websocket.WebSocketHandler):\n          def open(self):\n              print(\"WebSocket opened\")\n\n          def on_message(self, message):\n              self.write_message(u\"You said: \" + message)\n\n          def on_close(self):\n              print(\"WebSocket closed\")\n\n    .. testoutput::\n       :hide:\n\n    WebSockets are not standard HTTP connections. The \"handshake\" is\n    HTTP, but after the handshake, the protocol is\n    message-based. Consequently, most of the Tornado HTTP facilities\n    are not available in handlers of this type. The only communication\n    methods available to you are `write_message()`, `ping()`, and\n    `close()`. Likewise, your request handler class should implement\n    `open()` method rather than ``get()`` or ``post()``.\n\n    If you map the handler above to ``/websocket`` in your application, you can\n    invoke it in JavaScript with::\n\n      var ws = new WebSocket(\"ws://localhost:8888/websocket\");\n      ws.onopen = function() {\n         ws.send(\"Hello, world\");\n      };\n      ws.onmessage = function (evt) {\n         alert(evt.data);\n      };\n\n    This script pops up an alert box that says \"You said: Hello, world\".\n\n    Web browsers allow any site to open a websocket connection to any other,\n    instead of using the same-origin policy that governs other network\n    access from JavaScript.  This can be surprising and is a potential\n    security hole, so since Tornado 4.0 `WebSocketHandler` requires\n    applications that wish to receive cross-origin websockets to opt in\n    by overriding the `~WebSocketHandler.check_origin` method (see that\n    method's docs for details).  Failure to do so is the most likely\n    cause of 403 errors when making a websocket connection.\n\n    When using a secure websocket connection (``wss://``) with a self-signed\n    certificate, the connection from a browser may fail because it wants\n    to show the \"accept this certificate\" dialog but has nowhere to show it.\n    You must first visit a regular HTML page using the same certificate\n    to accept it before the websocket connection will succeed.\n\n    If the application setting ``websocket_ping_interval`` has a non-zero\n    value, a ping will be sent periodically, and the connection will be\n    closed if a response is not received before the ``websocket_ping_timeout``.\n\n    Messages larger than the ``websocket_max_message_size`` application setting\n    (default 10MiB) will not be accepted.\n\n    .. versionchanged:: 4.5\n       Added ``websocket_ping_interval``, ``websocket_ping_timeout``, and\n       ``websocket_max_message_size``.\n    \"\"\"\n\n    def __init__(\n        self,\n        application: tornado.web.Application,\n        request: httputil.HTTPServerRequest,\n        **kwargs: Any\n    ) -> None:\n        super().__init__(application, request, **kwargs)\n        self.ws_connection = None  # type: Optional[WebSocketProtocol]\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.stream = None  # type: Optional[IOStream]\n        self._on_close_called = False\n\n    async def get(self, *args: Any, **kwargs: Any) -> None:\n        self.open_args = args\n        self.open_kwargs = kwargs\n\n        # Upgrade header should be present and should be equal to WebSocket\n        if self.request.headers.get(\"Upgrade\", \"\").lower() != \"websocket\":\n            self.set_status(400)\n            log_msg = 'Can \"Upgrade\" only to \"WebSocket\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Connection header should be upgrade.\n        # Some proxy servers/load balancers\n        # might mess with it.\n        headers = self.request.headers\n        connection = map(\n            lambda s: s.strip().lower(), headers.get(\"Connection\", \"\").split(\",\")\n        )\n        if \"upgrade\" not in connection:\n            self.set_status(400)\n            log_msg = '\"Connection\" must be \"Upgrade\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Handle WebSocket Origin naming convention differences\n        # The difference between version 8 and 13 is that in 8 the\n        # client sends a \"Sec-Websocket-Origin\" header and in 13 it's\n        # simply \"Origin\".\n        if \"Origin\" in self.request.headers:\n            origin = self.request.headers.get(\"Origin\")\n        else:\n            origin = self.request.headers.get(\"Sec-Websocket-Origin\", None)\n\n        # If there was an origin header, check to make sure it matches\n        # according to check_origin. When the origin is None, we assume it\n        # did not come from a browser and that it can be passed on.\n        if origin is not None and not self.check_origin(origin):\n            self.set_status(403)\n            log_msg = \"Cross origin websockets not allowed\"\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        self.ws_connection = self.get_websocket_protocol()\n        if self.ws_connection:\n            await self.ws_connection.accept_connection(self)\n        else:\n            self.set_status(426, \"Upgrade Required\")\n            self.set_header(\"Sec-WebSocket-Version\", \"7, 8, 13\")\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        \"\"\"The interval for websocket keep-alive pings.\n\n        Set websocket_ping_interval = 0 to disable pings.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_interval\", None)\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        \"\"\"If no ping is received in this many seconds,\n        close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).\n        Default is max of 3 pings or 30 seconds.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_timeout\", None)\n\n    @property\n    def max_message_size(self) -> int:\n        \"\"\"Maximum allowed message size.\n\n        If the remote peer sends a message larger than this, the connection\n        will be closed.\n\n        Default is 10MiB.\n        \"\"\"\n        return self.settings.get(\n            \"websocket_max_message_size\", _default_max_message_size\n        )\n\n    def write_message(\n        self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\n\n        The message may be either a string or a dict (which will be\n        encoded as json).  If the ``binary`` argument is false, the\n        message will be sent as utf8; in binary mode any byte string\n        is allowed.\n\n        If the connection is already closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 3.2\n           `WebSocketClosedError` was added (previously a closed connection\n           would raise an `AttributeError`)\n\n        .. versionchanged:: 4.3\n           Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Consistently raises `WebSocketClosedError`. Previously could\n           sometimes raise `.StreamClosedError`.\n        \"\"\"\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        if isinstance(message, dict):\n            message = tornado.escape.json_encode(message)\n        return self.ws_connection.write_message(message, binary=binary)\n\n    def select_subprotocol(self, subprotocols: List[str]) -> Optional[str]:\n        \"\"\"Override to implement subprotocol negotiation.\n\n        ``subprotocols`` is a list of strings identifying the\n        subprotocols proposed by the client.  This method may be\n        overridden to return one of those strings to select it, or\n        ``None`` to not select a subprotocol.\n\n        Failure to select a subprotocol does not automatically abort\n        the connection, although clients may close the connection if\n        none of their proposed subprotocols was selected.\n\n        The list may be empty, in which case this method must return\n        None. This method is always called exactly once even if no\n        subprotocols were proposed so that the handler can be advised\n        of this fact.\n\n        .. versionchanged:: 5.1\n\n           Previously, this method was called with a list containing\n           an empty string instead of an empty list if no subprotocols\n           were proposed by the client.\n        \"\"\"\n        return None\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol returned by `select_subprotocol`.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        assert self.ws_connection is not None\n        return self.ws_connection.selected_subprotocol\n\n    def get_compression_options(self) -> Optional[Dict[str, Any]]:\n        \"\"\"Override to return compression options for the connection.\n\n        If this method returns None (the default), compression will\n        be disabled.  If it returns a dict (even an empty one), it\n        will be enabled.  The contents of the dict may be used to\n        control the following compression options:\n\n        ``compression_level`` specifies the compression level.\n\n        ``mem_level`` specifies the amount of memory used for the internal compression state.\n\n         These parameters are documented in details here:\n         https://docs.python.org/3.6/library/zlib.html#zlib.compressobj\n\n        .. versionadded:: 4.1\n\n        .. versionchanged:: 4.5\n\n           Added ``compression_level`` and ``mem_level``.\n        \"\"\"\n        # TODO: Add wbits option.\n        return None\n\n    def open(self, *args: str, **kwargs: str) -> Optional[Awaitable[None]]:\n        \"\"\"Invoked when a new WebSocket is opened.\n\n        The arguments to `open` are extracted from the `tornado.web.URLSpec`\n        regular expression, just like the arguments to\n        `tornado.web.RequestHandler.get`.\n\n        `open` may be a coroutine. `on_message` will not be called until\n        `open` has returned.\n\n        .. versionchanged:: 5.1\n\n           ``open`` may be a coroutine.\n        \"\"\"\n        pass\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        \"\"\"Handle incoming messages on the WebSocket\n\n        This method must be overridden.\n\n        .. versionchanged:: 4.5\n\n           ``on_message`` can be a coroutine.\n        \"\"\"\n        raise NotImplementedError\n\n    def ping(self, data: Union[str, bytes] = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``websocket_ping_interval`` application\n        setting instead of sending pings manually.\n\n        .. versionchanged:: 5.1\n\n           The data argument is now optional.\n\n        \"\"\"\n        data = utf8(data)\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        self.ws_connection.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        \"\"\"Invoked when the response to a ping frame is received.\"\"\"\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        \"\"\"Invoked when the a ping frame is received.\"\"\"\n        pass\n\n    def on_close(self) -> None:\n        \"\"\"Invoked when the WebSocket is closed.\n\n        If the connection was closed cleanly and a status code or reason\n        phrase was supplied, these values will be available as the attributes\n        ``self.close_code`` and ``self.close_reason``.\n\n        .. versionchanged:: 4.0\n\n           Added ``close_code`` and ``close_reason`` attributes.\n        \"\"\"\n        pass\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes this Web Socket.\n\n        Once the close handshake is successful the socket will be closed.\n\n        ``code`` may be a numeric status code, taken from the values\n        defined in `RFC 6455 section 7.4.1\n        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.\n        ``reason`` may be a textual message about why the connection is\n        closing.  These values are made available to the client, but are\n        not otherwise interpreted by the websocket protocol.\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.ws_connection:\n            self.ws_connection.close(code, reason)\n            self.ws_connection = None\n\n    def check_origin(self, origin: str) -> bool:\n        \"\"\"Override to enable support for allowing alternate origins.\n\n        The ``origin`` argument is the value of the ``Origin`` HTTP\n        header, the url responsible for initiating this request.  This\n        method is not called for clients that do not send this header;\n        such requests are always allowed (because all browsers that\n        implement WebSockets support this header, and non-browser\n        clients do not have the same cross-site security concerns).\n\n        Should return ``True`` to accept the request or ``False`` to\n        reject it. By default, rejects all requests with an origin on\n        a host other than this one.\n\n        This is a security protection against cross site scripting attacks on\n        browsers, since WebSockets are allowed to bypass the usual same-origin\n        policies and don't use CORS headers.\n\n        .. warning::\n\n           This is an important security measure; don't disable it\n           without understanding the security implications. In\n           particular, if your authentication is cookie-based, you\n           must either restrict the origins allowed by\n           ``check_origin()`` or implement your own XSRF-like\n           protection for websocket connections. See `these\n           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_\n           `articles\n           <https://devcenter.heroku.com/articles/websocket-security>`_\n           for more.\n\n        To accept all cross-origin traffic (which was the default prior to\n        Tornado 4.0), simply override this method to always return ``True``::\n\n            def check_origin(self, origin):\n                return True\n\n        To allow connections from any subdomain of your site, you might\n        do something like::\n\n            def check_origin(self, origin):\n                parsed_origin = urllib.parse.urlparse(origin)\n                return parsed_origin.netloc.endswith(\".mydomain.com\")\n\n        .. versionadded:: 4.0\n\n        \"\"\"\n        parsed_origin = urlparse(origin)\n        origin = parsed_origin.netloc\n        origin = origin.lower()\n\n        host = self.request.headers.get(\"Host\")\n\n        # Check to see that origin matches host directly, including ports\n        return origin == host\n\n    def set_nodelay(self, value: bool) -> None:\n        \"\"\"Set the no-delay flag for this stream.\n\n        By default, small messages may be delayed and/or combined to minimize\n        the number of packets sent.  This can sometimes cause 200-500ms delays\n        due to the interaction between Nagle's algorithm and TCP delayed\n        ACKs.  To reduce this delay (at the expense of possibly increasing\n        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket\n        connection is established.\n\n        See `.BaseIOStream.set_nodelay` for additional details.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        assert self.ws_connection is not None\n        self.ws_connection.set_nodelay(value)\n\n    def on_connection_close(self) -> None:\n        if self.ws_connection:\n            self.ws_connection.on_connection_close()\n            self.ws_connection = None\n        if not self._on_close_called:\n            self._on_close_called = True\n            self.on_close()\n            self._break_cycles()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _break_cycles(self) -> None:\n        # WebSocketHandlers call finish() early, but we don't want to\n        # break up reference cycles (which makes it impossible to call\n        # self.render_string) until after we've really closed the\n        # connection (if it was established in the first place,\n        # indicated by status code 101).\n        if self.get_status() != 101 or self._on_close_called:\n            super()._break_cycles()\n\n    def send_error(self, *args: Any, **kwargs: Any) -> None:\n        if self.stream is None:\n            super().send_error(*args, **kwargs)\n        else:\n            # If we get an uncaught exception during the handshake,\n            # we have no choice but to abruptly close the connection.\n            # TODO: for uncaught exceptions after the handshake,\n            # we can close the connection more gracefully.\n            self.stream.close()\n\n    def get_websocket_protocol(self) -> Optional[\"WebSocketProtocol\"]:\n        websocket_version = self.request.headers.get(\"Sec-WebSocket-Version\")\n        if websocket_version in (\"7\", \"8\", \"13\"):\n            params = _WebSocketParams(\n                ping_interval=self.ping_interval,\n                ping_timeout=self.ping_timeout,\n                max_message_size=self.max_message_size,\n                compression_options=self.get_compression_options(),\n            )\n            return WebSocketProtocol13(self, False, params)\n        return None\n\n    def _detach_stream(self) -> IOStream:\n        # disable non-WS methods\n        for method in [\n            \"write\",\n            \"redirect\",\n            \"set_header\",\n            \"set_cookie\",\n            \"set_status\",\n            \"flush\",\n            \"finish\",\n        ]:\n            setattr(self, method, _raise_not_supported_for_websockets)\n        return self.detach()\n\n\ndef _raise_not_supported_for_websockets(*args: Any, **kwargs: Any) -> None:\n    raise RuntimeError(\"Method not supported for Web Sockets\")\n\n\nclass WebSocketProtocol(abc.ABC):\n    \"\"\"Base class for WebSocket protocol versions.\n    \"\"\"\n\n    def __init__(self, handler: \"_WebSocketDelegate\") -> None:\n        self.handler = handler\n        self.stream = None  # type: Optional[IOStream]\n        self.client_terminated = False\n        self.server_terminated = False\n\n    def _run_callback(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> \"Optional[Future[Any]]\":\n        \"\"\"Runs the given callback with exception handling.\n\n        If the callback is a coroutine, returns its Future. On error, aborts the\n        websocket connection and returns None.\n        \"\"\"\n        try:\n            result = callback(*args, **kwargs)\n        except Exception:\n            self.handler.log_exception(*sys.exc_info())\n            self._abort()\n            return None\n        else:\n            if result is not None:\n                result = gen.convert_yielded(result)\n                assert self.stream is not None\n                self.stream.io_loop.add_future(result, lambda f: f.result())\n            return result\n\n    def on_connection_close(self) -> None:\n        self._abort()\n\n    def _abort(self) -> None:\n        \"\"\"Instantly aborts the WebSocket connection by closing the socket\"\"\"\n        self.client_terminated = True\n        self.server_terminated = True\n        if self.stream is not None:\n            self.stream.close()  # forcibly tear down the connection\n        self.close()  # let the subclass cleanup\n\n    @abc.abstractmethod\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def is_closing(self) -> bool:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        raise NotImplementedError()\n\n    @property\n    @abc.abstractmethod\n    def selected_subprotocol(self) -> Optional[str]:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_ping(self, data: bytes) -> None:\n        raise NotImplementedError()\n\n    # The entry points below are used by WebSocketClientConnection,\n    # which was introduced after we only supported a single version of\n    # WebSocketProtocol. The WebSocketProtocol/WebSocketProtocol13\n    # boundary is currently pretty ad-hoc.\n    @abc.abstractmethod\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def start_pinging(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def _receive_frame_loop(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def set_nodelay(self, x: bool) -> None:\n        raise NotImplementedError()\n\n\nclass _PerMessageDeflateCompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        # There is no symbolic constant for the minimum wbits value.\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n\n        if (\n            compression_options is None\n            or \"compression_level\" not in compression_options\n        ):\n            self._compression_level = tornado.web.GZipContentEncoding.GZIP_LEVEL\n        else:\n            self._compression_level = compression_options[\"compression_level\"]\n\n        if compression_options is None or \"mem_level\" not in compression_options:\n            self._mem_level = 8\n        else:\n            self._mem_level = compression_options[\"mem_level\"]\n\n        if persistent:\n            self._compressor = self._create_compressor()  # type: Optional[_Compressor]\n        else:\n            self._compressor = None\n\n    def _create_compressor(self) -> \"_Compressor\":\n        return zlib.compressobj(\n            self._compression_level, zlib.DEFLATED, -self._max_wbits, self._mem_level\n        )\n\n    def compress(self, data: bytes) -> bytes:\n        compressor = self._compressor or self._create_compressor()\n        data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)\n        assert data.endswith(b\"\\x00\\x00\\xff\\xff\")\n        return data[:-4]\n\n\nclass _PerMessageDeflateDecompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        max_message_size: int,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self._max_message_size = max_message_size\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n        if persistent:\n            self._decompressor = (\n                self._create_decompressor()\n            )  # type: Optional[_Decompressor]\n        else:\n            self._decompressor = None\n\n    def _create_decompressor(self) -> \"_Decompressor\":\n        return zlib.decompressobj(-self._max_wbits)\n\n    def decompress(self, data: bytes) -> bytes:\n        decompressor = self._decompressor or self._create_decompressor()\n        result = decompressor.decompress(\n            data + b\"\\x00\\x00\\xff\\xff\", self._max_message_size\n        )\n        if decompressor.unconsumed_tail:\n            raise _DecompressTooLargeError()\n        return result\n\n\nclass WebSocketProtocol13(WebSocketProtocol):\n    \"\"\"Implementation of the WebSocket protocol from RFC 6455.\n\n    This class supports versions 7 and 8 of the protocol in addition to the\n    final version 13.\n    \"\"\"\n\n    # Bit masks for the first byte of a frame.\n    FIN = 0x80\n    RSV1 = 0x40\n    RSV2 = 0x20\n    RSV3 = 0x10\n    RSV_MASK = RSV1 | RSV2 | RSV3\n    OPCODE_MASK = 0x0F\n\n    stream = None  # type: IOStream\n\n    def __init__(\n        self,\n        handler: \"_WebSocketDelegate\",\n        mask_outgoing: bool,\n        params: _WebSocketParams,\n    ) -> None:\n        WebSocketProtocol.__init__(self, handler)\n        self.mask_outgoing = mask_outgoing\n        self.params = params\n        self._final_frame = False\n        self._frame_opcode = None\n        self._masked_frame = None\n        self._frame_mask = None  # type: Optional[bytes]\n        self._frame_length = None\n        self._fragmented_message_buffer = None  # type: Optional[bytes]\n        self._fragmented_message_opcode = None\n        self._waiting = None  # type: object\n        self._compression_options = params.compression_options\n        self._decompressor = None  # type: Optional[_PerMessageDeflateDecompressor]\n        self._compressor = None  # type: Optional[_PerMessageDeflateCompressor]\n        self._frame_compressed = None  # type: Optional[bool]\n        # The total uncompressed size of all messages received or sent.\n        # Unicode messages are encoded to utf8.\n        # Only for testing; subject to change.\n        self._message_bytes_in = 0\n        self._message_bytes_out = 0\n        # The total size of all packets received or sent.  Includes\n        # the effect of compression, frame overhead, and control frames.\n        self._wire_bytes_in = 0\n        self._wire_bytes_out = 0\n        self.ping_callback = None  # type: Optional[PeriodicCallback]\n        self.last_ping = 0.0\n        self.last_pong = 0.0\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n\n    # Use a property for this to satisfy the abc.\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        return self._selected_subprotocol\n\n    @selected_subprotocol.setter\n    def selected_subprotocol(self, value: Optional[str]) -> None:\n        self._selected_subprotocol = value\n\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        try:\n            self._handle_websocket_headers(handler)\n        except ValueError:\n            handler.set_status(400)\n            log_msg = \"Missing/Invalid WebSocket headers\"\n            handler.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        try:\n            await self._accept_connection(handler)\n        except asyncio.CancelledError:\n            self._abort()\n            return\n        except ValueError:\n            gen_log.debug(\"Malformed WebSocket request received\", exc_info=True)\n            self._abort()\n            return\n\n    def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:\n        \"\"\"Verifies all invariant- and required headers\n\n        If a header is missing or have an incorrect value ValueError will be\n        raised\n        \"\"\"\n        fields = (\"Host\", \"Sec-Websocket-Key\", \"Sec-Websocket-Version\")\n        if not all(map(lambda f: handler.request.headers.get(f), fields)):\n            raise ValueError(\"Missing/Invalid WebSocket headers\")\n\n    @staticmethod\n    def compute_accept_value(key: Union[str, bytes]) -> str:\n        \"\"\"Computes the value for the Sec-WebSocket-Accept header,\n        given the value for Sec-WebSocket-Key.\n        \"\"\"\n        sha1 = hashlib.sha1()\n        sha1.update(utf8(key))\n        sha1.update(b\"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\")  # Magic value\n        return native_str(base64.b64encode(sha1.digest()))\n\n    def _challenge_response(self, handler: WebSocketHandler) -> str:\n        return WebSocketProtocol13.compute_accept_value(\n            cast(str, handler.request.headers.get(\"Sec-Websocket-Key\"))\n        )\n\n    async def _accept_connection(self, handler: WebSocketHandler) -> None:\n        subprotocol_header = handler.request.headers.get(\"Sec-WebSocket-Protocol\")\n        if subprotocol_header:\n            subprotocols = [s.strip() for s in subprotocol_header.split(\",\")]\n        else:\n            subprotocols = []\n        self.selected_subprotocol = handler.select_subprotocol(subprotocols)\n        if self.selected_subprotocol:\n            assert self.selected_subprotocol in subprotocols\n            handler.set_header(\"Sec-WebSocket-Protocol\", self.selected_subprotocol)\n\n        extensions = self._parse_extensions_header(handler.request.headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                # TODO: negotiate parameters if compression_options\n                # specifies limits.\n                self._create_compressors(\"server\", ext[1], self._compression_options)\n                if (\n                    \"client_max_window_bits\" in ext[1]\n                    and ext[1][\"client_max_window_bits\"] is None\n                ):\n                    # Don't echo an offered client_max_window_bits\n                    # parameter with no value.\n                    del ext[1][\"client_max_window_bits\"]\n                handler.set_header(\n                    \"Sec-WebSocket-Extensions\",\n                    httputil._encode_header(\"permessage-deflate\", ext[1]),\n                )\n                break\n\n        handler.clear_header(\"Content-Type\")\n        handler.set_status(101)\n        handler.set_header(\"Upgrade\", \"websocket\")\n        handler.set_header(\"Connection\", \"Upgrade\")\n        handler.set_header(\"Sec-WebSocket-Accept\", self._challenge_response(handler))\n        handler.finish()\n\n        self.stream = handler._detach_stream()\n\n        self.start_pinging()\n        try:\n            open_result = handler.open(*handler.open_args, **handler.open_kwargs)\n            if open_result is not None:\n                await open_result\n        except Exception:\n            handler.log_exception(*sys.exc_info())\n            self._abort()\n            return\n\n        await self._receive_frame_loop()\n\n    def _parse_extensions_header(\n        self, headers: httputil.HTTPHeaders\n    ) -> List[Tuple[str, Dict[str, str]]]:\n        extensions = headers.get(\"Sec-WebSocket-Extensions\", \"\")\n        if extensions:\n            return [httputil._parse_header(e.strip()) for e in extensions.split(\",\")]\n        return []\n\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        \"\"\"Process the headers sent by the server to this client connection.\n\n        'key' is the websocket handshake challenge/response key.\n        \"\"\"\n        assert headers[\"Upgrade\"].lower() == \"websocket\"\n        assert headers[\"Connection\"].lower() == \"upgrade\"\n        accept = self.compute_accept_value(key)\n        assert headers[\"Sec-Websocket-Accept\"] == accept\n\n        extensions = self._parse_extensions_header(headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                self._create_compressors(\"client\", ext[1])\n            else:\n                raise ValueError(\"unsupported extension %r\", ext)\n\n        self.selected_subprotocol = headers.get(\"Sec-WebSocket-Protocol\", None)\n\n    def _get_compressor_options(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Converts a websocket agreed_parameters set to keyword arguments\n        for our compressor objects.\n        \"\"\"\n        options = dict(\n            persistent=(side + \"_no_context_takeover\") not in agreed_parameters\n        )  # type: Dict[str, Any]\n        wbits_header = agreed_parameters.get(side + \"_max_window_bits\", None)\n        if wbits_header is None:\n            options[\"max_wbits\"] = zlib.MAX_WBITS\n        else:\n            options[\"max_wbits\"] = int(wbits_header)\n        options[\"compression_options\"] = compression_options\n        return options\n\n    def _create_compressors(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        # TODO: handle invalid parameters gracefully\n        allowed_keys = set(\n            [\n                \"server_no_context_takeover\",\n                \"client_no_context_takeover\",\n                \"server_max_window_bits\",\n                \"client_max_window_bits\",\n            ]\n        )\n        for key in agreed_parameters:\n            if key not in allowed_keys:\n                raise ValueError(\"unsupported compression parameter %r\" % key)\n        other_side = \"client\" if (side == \"server\") else \"server\"\n        self._compressor = _PerMessageDeflateCompressor(\n            **self._get_compressor_options(side, agreed_parameters, compression_options)\n        )\n        self._decompressor = _PerMessageDeflateDecompressor(\n            max_message_size=self.params.max_message_size,\n            **self._get_compressor_options(\n                other_side, agreed_parameters, compression_options\n            )\n        )\n\n    def _write_frame(\n        self, fin: bool, opcode: int, data: bytes, flags: int = 0\n    ) -> \"Future[None]\":\n        data_len = len(data)\n        if opcode & 0x8:\n            # All control frames MUST have a payload length of 125\n            # bytes or less and MUST NOT be fragmented.\n            if not fin:\n                raise ValueError(\"control frames may not be fragmented\")\n            if data_len > 125:\n                raise ValueError(\"control frame payloads may not exceed 125 bytes\")\n        if fin:\n            finbit = self.FIN\n        else:\n            finbit = 0\n        frame = struct.pack(\"B\", finbit | opcode | flags)\n        if self.mask_outgoing:\n            mask_bit = 0x80\n        else:\n            mask_bit = 0\n        if data_len < 126:\n            frame += struct.pack(\"B\", data_len | mask_bit)\n        elif data_len <= 0xFFFF:\n            frame += struct.pack(\"!BH\", 126 | mask_bit, data_len)\n        else:\n            frame += struct.pack(\"!BQ\", 127 | mask_bit, data_len)\n        if self.mask_outgoing:\n            mask = os.urandom(4)\n            data = mask + _websocket_mask(mask, data)\n        frame += data\n        self._wire_bytes_out += len(frame)\n        return self.stream.write(frame)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\"\"\"\n        if binary:\n            opcode = 0x2\n        else:\n            opcode = 0x1\n        message = tornado.escape.utf8(message)\n        assert isinstance(message, bytes)\n        self._message_bytes_out += len(message)\n        flags = 0\n        if self._compressor:\n            message = self._compressor.compress(message)\n            flags |= self.RSV1\n        # For historical reasons, write methods in Tornado operate in a semi-synchronous\n        # mode in which awaiting the Future they return is optional (But errors can\n        # still be raised). This requires us to go through an awkward dance here\n        # to transform the errors that may be returned while presenting the same\n        # semi-synchronous interface.\n        try:\n            fut = self._write_frame(True, opcode, message, flags=flags)\n        except StreamClosedError:\n            raise WebSocketClosedError()\n\n        async def wrapper() -> None:\n            try:\n                await fut\n            except StreamClosedError:\n                raise WebSocketClosedError()\n\n        return asyncio.ensure_future(wrapper())\n\n    def write_ping(self, data: bytes) -> None:\n        \"\"\"Send ping frame.\"\"\"\n        assert isinstance(data, bytes)\n        self._write_frame(True, 0x9, data)\n\n    async def _receive_frame_loop(self) -> None:\n        try:\n            while not self.client_terminated:\n                await self._receive_frame()\n        except StreamClosedError:\n            self._abort()\n        self.handler.on_ws_connection_close(self.close_code, self.close_reason)\n\n    async def _read_bytes(self, n: int) -> bytes:\n        data = await self.stream.read_bytes(n)\n        self._wire_bytes_in += n\n        return data\n\n    async def _receive_frame(self) -> None:\n        # Read the frame header.\n        data = await self._read_bytes(2)\n        header, mask_payloadlen = struct.unpack(\"BB\", data)\n        is_final_frame = header & self.FIN\n        reserved_bits = header & self.RSV_MASK\n        opcode = header & self.OPCODE_MASK\n        opcode_is_control = opcode & 0x8\n        if self._decompressor is not None and opcode != 0:\n            # Compression flag is present in the first frame's header,\n            # but we can't decompress until we have all the frames of\n            # the message.\n            self._frame_compressed = bool(reserved_bits & self.RSV1)\n            reserved_bits &= ~self.RSV1\n        if reserved_bits:\n            # client is using as-yet-undefined extensions; abort\n            self._abort()\n            return\n        is_masked = bool(mask_payloadlen & 0x80)\n        payloadlen = mask_payloadlen & 0x7F\n\n        # Parse and validate the length.\n        if opcode_is_control and payloadlen >= 126:\n            # control frames must have payload < 126\n            self._abort()\n            return\n        if payloadlen < 126:\n            self._frame_length = payloadlen\n        elif payloadlen == 126:\n            data = await self._read_bytes(2)\n            payloadlen = struct.unpack(\"!H\", data)[0]\n        elif payloadlen == 127:\n            data = await self._read_bytes(8)\n            payloadlen = struct.unpack(\"!Q\", data)[0]\n        new_len = payloadlen\n        if self._fragmented_message_buffer is not None:\n            new_len += len(self._fragmented_message_buffer)\n        if new_len > self.params.max_message_size:\n            self.close(1009, \"message too big\")\n            self._abort()\n            return\n\n        # Read the payload, unmasking if necessary.\n        if is_masked:\n            self._frame_mask = await self._read_bytes(4)\n        data = await self._read_bytes(payloadlen)\n        if is_masked:\n            assert self._frame_mask is not None\n            data = _websocket_mask(self._frame_mask, data)\n\n        # Decide what to do with this frame.\n        if opcode_is_control:\n            # control frames may be interleaved with a series of fragmented\n            # data frames, so control frames must not interact with\n            # self._fragmented_*\n            if not is_final_frame:\n                # control frames must not be fragmented\n                self._abort()\n                return\n        elif opcode == 0:  # continuation frame\n            if self._fragmented_message_buffer is None:\n                # nothing to continue\n                self._abort()\n                return\n            self._fragmented_message_buffer += data\n            if is_final_frame:\n                opcode = self._fragmented_message_opcode\n                data = self._fragmented_message_buffer\n                self._fragmented_message_buffer = None\n        else:  # start of new data message\n            if self._fragmented_message_buffer is not None:\n                # can't start new message until the old one is finished\n                self._abort()\n                return\n            if not is_final_frame:\n                self._fragmented_message_opcode = opcode\n                self._fragmented_message_buffer = data\n\n        if is_final_frame:\n            handled_future = self._handle_message(opcode, data)\n            if handled_future is not None:\n                await handled_future\n\n    def _handle_message(self, opcode: int, data: bytes) -> \"Optional[Future[None]]\":\n        \"\"\"Execute on_message, returning its Future if it is a coroutine.\"\"\"\n        if self.client_terminated:\n            return None\n\n        if self._frame_compressed:\n            assert self._decompressor is not None\n            try:\n                data = self._decompressor.decompress(data)\n            except _DecompressTooLargeError:\n                self.close(1009, \"message too big after decompression\")\n                self._abort()\n                return None\n\n        if opcode == 0x1:\n            # UTF-8 data\n            self._message_bytes_in += len(data)\n            try:\n                decoded = data.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                self._abort()\n                return None\n            return self._run_callback(self.handler.on_message, decoded)\n        elif opcode == 0x2:\n            # Binary data\n            self._message_bytes_in += len(data)\n            return self._run_callback(self.handler.on_message, data)\n        elif opcode == 0x8:\n            # Close\n            self.client_terminated = True\n            if len(data) >= 2:\n                self.close_code = struct.unpack(\">H\", data[:2])[0]\n            if len(data) > 2:\n                self.close_reason = to_unicode(data[2:])\n            # Echo the received close code, if any (RFC 6455 section 5.5.1).\n            self.close(self.close_code)\n        elif opcode == 0x9:\n            # Ping\n            try:\n                self._write_frame(True, 0xA, data)\n            except StreamClosedError:\n                self._abort()\n            self._run_callback(self.handler.on_ping, data)\n        elif opcode == 0xA:\n            # Pong\n            self.last_pong = IOLoop.current().time()\n            return self._run_callback(self.handler.on_pong, data)\n        else:\n            self._abort()\n        return None\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the WebSocket connection.\"\"\"\n        if not self.server_terminated:\n            if not self.stream.closed():\n                if code is None and reason is not None:\n                    code = 1000  # \"normal closure\" status code\n                if code is None:\n                    close_data = b\"\"\n                else:\n                    close_data = struct.pack(\">H\", code)\n                if reason is not None:\n                    close_data += utf8(reason)\n                try:\n                    self._write_frame(True, 0x8, close_data)\n                except StreamClosedError:\n                    self._abort()\n            self.server_terminated = True\n        if self.client_terminated:\n            if self._waiting is not None:\n                self.stream.io_loop.remove_timeout(self._waiting)\n                self._waiting = None\n            self.stream.close()\n        elif self._waiting is None:\n            # Give the client a few seconds to complete a clean shutdown,\n            # otherwise just close the connection.\n            self._waiting = self.stream.io_loop.add_timeout(\n                self.stream.io_loop.time() + 5, self._abort\n            )\n        if self.ping_callback:\n            self.ping_callback.stop()\n            self.ping_callback = None\n\n    def is_closing(self) -> bool:\n        \"\"\"Return ``True`` if this connection is closing.\n\n        The connection is considered closing if either side has\n        initiated its closing handshake or if the stream has been\n        shut down uncleanly.\n        \"\"\"\n        return self.stream.closed() or self.client_terminated or self.server_terminated\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        interval = self.params.ping_interval\n        if interval is not None:\n            return interval\n        return 0\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        timeout = self.params.ping_timeout\n        if timeout is not None:\n            return timeout\n        assert self.ping_interval is not None\n        return max(3 * self.ping_interval, 30)\n\n    def start_pinging(self) -> None:\n        \"\"\"Start sending periodic pings to keep the connection alive\"\"\"\n        assert self.ping_interval is not None\n        if self.ping_interval > 0:\n            self.last_ping = self.last_pong = IOLoop.current().time()\n            self.ping_callback = PeriodicCallback(\n                self.periodic_ping, self.ping_interval * 1000\n            )\n            self.ping_callback.start()\n\n    def periodic_ping(self) -> None:\n        \"\"\"Send a ping to keep the websocket alive\n\n        Called periodically if the websocket_ping_interval is set and non-zero.\n        \"\"\"\n        if self.is_closing() and self.ping_callback is not None:\n            self.ping_callback.stop()\n            return\n\n        # Check for timeout on pong. Make sure that we really have\n        # sent a recent ping in case the machine with both server and\n        # client has been suspended since the last ping.\n        now = IOLoop.current().time()\n        since_last_pong = now - self.last_pong\n        since_last_ping = now - self.last_ping\n        assert self.ping_interval is not None\n        assert self.ping_timeout is not None\n        if (\n            since_last_ping < 2 * self.ping_interval\n            and since_last_pong > self.ping_timeout\n        ):\n            self.close()\n            return\n\n        self.write_ping(b\"\")\n        self.last_ping = now\n\n    def set_nodelay(self, x: bool) -> None:\n        self.stream.set_nodelay(x)\n\n\nclass WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))\n\n\ndef websocket_connect(\n    url: Union[str, httpclient.HTTPRequest],\n    callback: Optional[Callable[[\"Future[WebSocketClientConnection]\"], None]] = None,\n    connect_timeout: Optional[float] = None,\n    on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n    compression_options: Optional[Dict[str, Any]] = None,\n    ping_interval: Optional[float] = None,\n    ping_timeout: Optional[float] = None,\n    max_message_size: int = _default_max_message_size,\n    subprotocols: Optional[List[str]] = None,\n) -> \"Awaitable[WebSocketClientConnection]\":\n    \"\"\"Client-side websocket support.\n\n    Takes a url and returns a Future whose result is a\n    `WebSocketClientConnection`.\n\n    ``compression_options`` is interpreted in the same way as the\n    return value of `.WebSocketHandler.get_compression_options`.\n\n    The connection supports two styles of operation. In the coroutine\n    style, the application typically calls\n    `~.WebSocketClientConnection.read_message` in a loop::\n\n        conn = yield websocket_connect(url)\n        while True:\n            msg = yield conn.read_message()\n            if msg is None: break\n            # Do something with msg\n\n    In the callback style, pass an ``on_message_callback`` to\n    ``websocket_connect``. In both styles, a message of ``None``\n    indicates that the connection has been closed.\n\n    ``subprotocols`` may be a list of strings specifying proposed\n    subprotocols. The selected protocol may be found on the\n    ``selected_subprotocol`` attribute of the connection object\n    when the connection is complete.\n\n    .. versionchanged:: 3.2\n       Also accepts ``HTTPRequest`` objects in place of urls.\n\n    .. versionchanged:: 4.1\n       Added ``compression_options`` and ``on_message_callback``.\n\n    .. versionchanged:: 4.5\n       Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size``\n       arguments, which have the same meaning as in `WebSocketHandler`.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       Added the ``subprotocols`` argument.\n    \"\"\"\n    if isinstance(url, httpclient.HTTPRequest):\n        assert connect_timeout is None\n        request = url\n        # Copy and convert the headers dict/object (see comments in\n        # AsyncHTTPClient.fetch)\n        request.headers = httputil.HTTPHeaders(request.headers)\n    else:\n        request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)\n    request = cast(\n        httpclient.HTTPRequest,\n        httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS),\n    )\n    conn = WebSocketClientConnection(\n        request,\n        on_message_callback=on_message_callback,\n        compression_options=compression_options,\n        ping_interval=ping_interval,\n        ping_timeout=ping_timeout,\n        max_message_size=max_message_size,\n        subprotocols=subprotocols,\n    )\n    if callback is not None:\n        IOLoop.current().add_future(conn.connect_future, callback)\n    return conn.connect_future\n",
            "new_file_content": "\"\"\"Implementation of the WebSocket protocol.\n\n`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional\ncommunication between the browser and server.\n\nWebSockets are supported in the current versions of all major browsers,\nalthough older versions that do not support WebSockets are still in use\n(refer to http://caniuse.com/websockets for details).\n\nThis module implements the final version of the WebSocket protocol as\ndefined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_.  Certain\nbrowser versions (notably Safari 5.x) implemented an earlier draft of\nthe protocol (known as \"draft 76\") and are not compatible with this module.\n\n.. versionchanged:: 4.0\n   Removed support for the draft 76 protocol version.\n\"\"\"\n\nimport abc\nimport asyncio\nimport base64\nimport hashlib\nimport os\nimport sys\nimport struct\nimport tornado.escape\nimport tornado.web\nfrom urllib.parse import urlparse\nimport zlib\n\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.escape import utf8, native_str, to_unicode\nfrom tornado import gen, httpclient, httputil\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.log import gen_log, app_log\nfrom tornado import simple_httpclient\nfrom tornado.queues import Queue\nfrom tornado.tcpclient import TCPClient\nfrom tornado.util import _websocket_mask\n\nfrom typing import (\n    TYPE_CHECKING,\n    cast,\n    Any,\n    Optional,\n    Dict,\n    Union,\n    List,\n    Awaitable,\n    Callable,\n    Tuple,\n    Type,\n)\nfrom types import TracebackType\n\nif TYPE_CHECKING:\n    from typing_extensions import Protocol\n\n    # The zlib compressor types aren't actually exposed anywhere\n    # publicly, so declare protocols for the portions we use.\n    class _Compressor(Protocol):\n        def compress(self, data: bytes) -> bytes:\n            pass\n\n        def flush(self, mode: int) -> bytes:\n            pass\n\n    class _Decompressor(Protocol):\n        unconsumed_tail = b\"\"  # type: bytes\n\n        def decompress(self, data: bytes, max_length: int) -> bytes:\n            pass\n\n    class _WebSocketDelegate(Protocol):\n        # The common base interface implemented by WebSocketHandler on\n        # the server side and WebSocketClientConnection on the client\n        # side.\n        def on_ws_connection_close(\n            self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n        ) -> None:\n            pass\n\n        def on_message(self, message: Union[str, bytes]) -> Optional[\"Awaitable[None]\"]:\n            pass\n\n        def on_ping(self, data: bytes) -> None:\n            pass\n\n        def on_pong(self, data: bytes) -> None:\n            pass\n\n        def log_exception(\n            self,\n            typ: Optional[Type[BaseException]],\n            value: Optional[BaseException],\n            tb: Optional[TracebackType],\n        ) -> None:\n            pass\n\n\n_default_max_message_size = 10 * 1024 * 1024\n\n\nclass WebSocketError(Exception):\n    pass\n\n\nclass WebSocketClosedError(WebSocketError):\n    \"\"\"Raised by operations on a closed connection.\n\n    .. versionadded:: 3.2\n    \"\"\"\n\n    pass\n\n\nclass _DecompressTooLargeError(Exception):\n    pass\n\n\nclass _WebSocketParams(object):\n    def __init__(\n        self,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self.ping_interval = ping_interval\n        self.ping_timeout = ping_timeout\n        self.max_message_size = max_message_size\n        self.compression_options = compression_options\n\n\nclass WebSocketHandler(tornado.web.RequestHandler):\n    \"\"\"Subclass this class to create a basic WebSocket handler.\n\n    Override `on_message` to handle incoming messages, and use\n    `write_message` to send messages to the client. You can also\n    override `open` and `on_close` to handle opened and closed\n    connections.\n\n    Custom upgrade response headers can be sent by overriding\n    `~tornado.web.RequestHandler.set_default_headers` or\n    `~tornado.web.RequestHandler.prepare`.\n\n    See http://dev.w3.org/html5/websockets/ for details on the\n    JavaScript interface.  The protocol is specified at\n    http://tools.ietf.org/html/rfc6455.\n\n    Here is an example WebSocket handler that echos back all received messages\n    back to the client:\n\n    .. testcode::\n\n      class EchoWebSocket(tornado.websocket.WebSocketHandler):\n          def open(self):\n              print(\"WebSocket opened\")\n\n          def on_message(self, message):\n              self.write_message(u\"You said: \" + message)\n\n          def on_close(self):\n              print(\"WebSocket closed\")\n\n    .. testoutput::\n       :hide:\n\n    WebSockets are not standard HTTP connections. The \"handshake\" is\n    HTTP, but after the handshake, the protocol is\n    message-based. Consequently, most of the Tornado HTTP facilities\n    are not available in handlers of this type. The only communication\n    methods available to you are `write_message()`, `ping()`, and\n    `close()`. Likewise, your request handler class should implement\n    `open()` method rather than ``get()`` or ``post()``.\n\n    If you map the handler above to ``/websocket`` in your application, you can\n    invoke it in JavaScript with::\n\n      var ws = new WebSocket(\"ws://localhost:8888/websocket\");\n      ws.onopen = function() {\n         ws.send(\"Hello, world\");\n      };\n      ws.onmessage = function (evt) {\n         alert(evt.data);\n      };\n\n    This script pops up an alert box that says \"You said: Hello, world\".\n\n    Web browsers allow any site to open a websocket connection to any other,\n    instead of using the same-origin policy that governs other network\n    access from JavaScript.  This can be surprising and is a potential\n    security hole, so since Tornado 4.0 `WebSocketHandler` requires\n    applications that wish to receive cross-origin websockets to opt in\n    by overriding the `~WebSocketHandler.check_origin` method (see that\n    method's docs for details).  Failure to do so is the most likely\n    cause of 403 errors when making a websocket connection.\n\n    When using a secure websocket connection (``wss://``) with a self-signed\n    certificate, the connection from a browser may fail because it wants\n    to show the \"accept this certificate\" dialog but has nowhere to show it.\n    You must first visit a regular HTML page using the same certificate\n    to accept it before the websocket connection will succeed.\n\n    If the application setting ``websocket_ping_interval`` has a non-zero\n    value, a ping will be sent periodically, and the connection will be\n    closed if a response is not received before the ``websocket_ping_timeout``.\n\n    Messages larger than the ``websocket_max_message_size`` application setting\n    (default 10MiB) will not be accepted.\n\n    .. versionchanged:: 4.5\n       Added ``websocket_ping_interval``, ``websocket_ping_timeout``, and\n       ``websocket_max_message_size``.\n    \"\"\"\n\n    def __init__(\n        self,\n        application: tornado.web.Application,\n        request: httputil.HTTPServerRequest,\n        **kwargs: Any\n    ) -> None:\n        super().__init__(application, request, **kwargs)\n        self.ws_connection = None  # type: Optional[WebSocketProtocol]\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.stream = None  # type: Optional[IOStream]\n        self._on_close_called = False\n\n    async def get(self, *args: Any, **kwargs: Any) -> None:\n        self.open_args = args\n        self.open_kwargs = kwargs\n\n        # Upgrade header should be present and should be equal to WebSocket\n        if self.request.headers.get(\"Upgrade\", \"\").lower() != \"websocket\":\n            self.set_status(400)\n            log_msg = 'Can \"Upgrade\" only to \"WebSocket\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Connection header should be upgrade.\n        # Some proxy servers/load balancers\n        # might mess with it.\n        headers = self.request.headers\n        connection = map(\n            lambda s: s.strip().lower(), headers.get(\"Connection\", \"\").split(\",\")\n        )\n        if \"upgrade\" not in connection:\n            self.set_status(400)\n            log_msg = '\"Connection\" must be \"Upgrade\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Handle WebSocket Origin naming convention differences\n        # The difference between version 8 and 13 is that in 8 the\n        # client sends a \"Sec-Websocket-Origin\" header and in 13 it's\n        # simply \"Origin\".\n        if \"Origin\" in self.request.headers:\n            origin = self.request.headers.get(\"Origin\")\n        else:\n            origin = self.request.headers.get(\"Sec-Websocket-Origin\", None)\n\n        # If there was an origin header, check to make sure it matches\n        # according to check_origin. When the origin is None, we assume it\n        # did not come from a browser and that it can be passed on.\n        if origin is not None and not self.check_origin(origin):\n            self.set_status(403)\n            log_msg = \"Cross origin websockets not allowed\"\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        self.ws_connection = self.get_websocket_protocol()\n        if self.ws_connection:\n            await self.ws_connection.accept_connection(self)\n        else:\n            self.set_status(426, \"Upgrade Required\")\n            self.set_header(\"Sec-WebSocket-Version\", \"7, 8, 13\")\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        \"\"\"The interval for websocket keep-alive pings.\n\n        Set websocket_ping_interval = 0 to disable pings.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_interval\", None)\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        \"\"\"If no ping is received in this many seconds,\n        close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).\n        Default is max of 3 pings or 30 seconds.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_timeout\", None)\n\n    @property\n    def max_message_size(self) -> int:\n        \"\"\"Maximum allowed message size.\n\n        If the remote peer sends a message larger than this, the connection\n        will be closed.\n\n        Default is 10MiB.\n        \"\"\"\n        return self.settings.get(\n            \"websocket_max_message_size\", _default_max_message_size\n        )\n\n    def write_message(\n        self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\n\n        The message may be either a string or a dict (which will be\n        encoded as json).  If the ``binary`` argument is false, the\n        message will be sent as utf8; in binary mode any byte string\n        is allowed.\n\n        If the connection is already closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 3.2\n           `WebSocketClosedError` was added (previously a closed connection\n           would raise an `AttributeError`)\n\n        .. versionchanged:: 4.3\n           Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Consistently raises `WebSocketClosedError`. Previously could\n           sometimes raise `.StreamClosedError`.\n        \"\"\"\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        if isinstance(message, dict):\n            message = tornado.escape.json_encode(message)\n        return self.ws_connection.write_message(message, binary=binary)\n\n    def select_subprotocol(self, subprotocols: List[str]) -> Optional[str]:\n        \"\"\"Override to implement subprotocol negotiation.\n\n        ``subprotocols`` is a list of strings identifying the\n        subprotocols proposed by the client.  This method may be\n        overridden to return one of those strings to select it, or\n        ``None`` to not select a subprotocol.\n\n        Failure to select a subprotocol does not automatically abort\n        the connection, although clients may close the connection if\n        none of their proposed subprotocols was selected.\n\n        The list may be empty, in which case this method must return\n        None. This method is always called exactly once even if no\n        subprotocols were proposed so that the handler can be advised\n        of this fact.\n\n        .. versionchanged:: 5.1\n\n           Previously, this method was called with a list containing\n           an empty string instead of an empty list if no subprotocols\n           were proposed by the client.\n        \"\"\"\n        return None\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol returned by `select_subprotocol`.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        assert self.ws_connection is not None\n        return self.ws_connection.selected_subprotocol\n\n    def get_compression_options(self) -> Optional[Dict[str, Any]]:\n        \"\"\"Override to return compression options for the connection.\n\n        If this method returns None (the default), compression will\n        be disabled.  If it returns a dict (even an empty one), it\n        will be enabled.  The contents of the dict may be used to\n        control the following compression options:\n\n        ``compression_level`` specifies the compression level.\n\n        ``mem_level`` specifies the amount of memory used for the internal compression state.\n\n         These parameters are documented in details here:\n         https://docs.python.org/3.6/library/zlib.html#zlib.compressobj\n\n        .. versionadded:: 4.1\n\n        .. versionchanged:: 4.5\n\n           Added ``compression_level`` and ``mem_level``.\n        \"\"\"\n        # TODO: Add wbits option.\n        return None\n\n    def open(self, *args: str, **kwargs: str) -> Optional[Awaitable[None]]:\n        \"\"\"Invoked when a new WebSocket is opened.\n\n        The arguments to `open` are extracted from the `tornado.web.URLSpec`\n        regular expression, just like the arguments to\n        `tornado.web.RequestHandler.get`.\n\n        `open` may be a coroutine. `on_message` will not be called until\n        `open` has returned.\n\n        .. versionchanged:: 5.1\n\n           ``open`` may be a coroutine.\n        \"\"\"\n        pass\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        \"\"\"Handle incoming messages on the WebSocket\n\n        This method must be overridden.\n\n        .. versionchanged:: 4.5\n\n           ``on_message`` can be a coroutine.\n        \"\"\"\n        raise NotImplementedError\n\n    def ping(self, data: Union[str, bytes] = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``websocket_ping_interval`` application\n        setting instead of sending pings manually.\n\n        .. versionchanged:: 5.1\n\n           The data argument is now optional.\n\n        \"\"\"\n        data = utf8(data)\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        self.ws_connection.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        \"\"\"Invoked when the response to a ping frame is received.\"\"\"\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        \"\"\"Invoked when the a ping frame is received.\"\"\"\n        pass\n\n    def on_close(self) -> None:\n        \"\"\"Invoked when the WebSocket is closed.\n\n        If the connection was closed cleanly and a status code or reason\n        phrase was supplied, these values will be available as the attributes\n        ``self.close_code`` and ``self.close_reason``.\n\n        .. versionchanged:: 4.0\n\n           Added ``close_code`` and ``close_reason`` attributes.\n        \"\"\"\n        pass\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes this Web Socket.\n\n        Once the close handshake is successful the socket will be closed.\n\n        ``code`` may be a numeric status code, taken from the values\n        defined in `RFC 6455 section 7.4.1\n        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.\n        ``reason`` may be a textual message about why the connection is\n        closing.  These values are made available to the client, but are\n        not otherwise interpreted by the websocket protocol.\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.ws_connection:\n            self.ws_connection.close(code, reason)\n            self.ws_connection = None\n\n    def check_origin(self, origin: str) -> bool:\n        \"\"\"Override to enable support for allowing alternate origins.\n\n        The ``origin`` argument is the value of the ``Origin`` HTTP\n        header, the url responsible for initiating this request.  This\n        method is not called for clients that do not send this header;\n        such requests are always allowed (because all browsers that\n        implement WebSockets support this header, and non-browser\n        clients do not have the same cross-site security concerns).\n\n        Should return ``True`` to accept the request or ``False`` to\n        reject it. By default, rejects all requests with an origin on\n        a host other than this one.\n\n        This is a security protection against cross site scripting attacks on\n        browsers, since WebSockets are allowed to bypass the usual same-origin\n        policies and don't use CORS headers.\n\n        .. warning::\n\n           This is an important security measure; don't disable it\n           without understanding the security implications. In\n           particular, if your authentication is cookie-based, you\n           must either restrict the origins allowed by\n           ``check_origin()`` or implement your own XSRF-like\n           protection for websocket connections. See `these\n           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_\n           `articles\n           <https://devcenter.heroku.com/articles/websocket-security>`_\n           for more.\n\n        To accept all cross-origin traffic (which was the default prior to\n        Tornado 4.0), simply override this method to always return ``True``::\n\n            def check_origin(self, origin):\n                return True\n\n        To allow connections from any subdomain of your site, you might\n        do something like::\n\n            def check_origin(self, origin):\n                parsed_origin = urllib.parse.urlparse(origin)\n                return parsed_origin.netloc.endswith(\".mydomain.com\")\n\n        .. versionadded:: 4.0\n\n        \"\"\"\n        parsed_origin = urlparse(origin)\n        origin = parsed_origin.netloc\n        origin = origin.lower()\n\n        host = self.request.headers.get(\"Host\")\n\n        # Check to see that origin matches host directly, including ports\n        return origin == host\n\n    def set_nodelay(self, value: bool) -> None:\n        \"\"\"Set the no-delay flag for this stream.\n\n        By default, small messages may be delayed and/or combined to minimize\n        the number of packets sent.  This can sometimes cause 200-500ms delays\n        due to the interaction between Nagle's algorithm and TCP delayed\n        ACKs.  To reduce this delay (at the expense of possibly increasing\n        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket\n        connection is established.\n\n        See `.BaseIOStream.set_nodelay` for additional details.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        assert self.ws_connection is not None\n        self.ws_connection.set_nodelay(value)\n\n    def on_connection_close(self) -> None:\n        if self.ws_connection:\n            self.ws_connection.on_connection_close()\n            self.ws_connection = None\n        if not self._on_close_called:\n            self._on_close_called = True\n            self.on_close()\n            self._break_cycles()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _break_cycles(self) -> None:\n        # WebSocketHandlers call finish() early, but we don't want to\n        # break up reference cycles (which makes it impossible to call\n        # self.render_string) until after we've really closed the\n        # connection (if it was established in the first place,\n        # indicated by status code 101).\n        if self.get_status() != 101 or self._on_close_called:\n            super()._break_cycles()\n\n    def send_error(self, *args: Any, **kwargs: Any) -> None:\n        if self.stream is None:\n            super().send_error(*args, **kwargs)\n        else:\n            # If we get an uncaught exception during the handshake,\n            # we have no choice but to abruptly close the connection.\n            # TODO: for uncaught exceptions after the handshake,\n            # we can close the connection more gracefully.\n            self.stream.close()\n\n    def get_websocket_protocol(self) -> Optional[\"WebSocketProtocol\"]:\n        websocket_version = self.request.headers.get(\"Sec-WebSocket-Version\")\n        if websocket_version in (\"7\", \"8\", \"13\"):\n            params = _WebSocketParams(\n                ping_interval=self.ping_interval,\n                ping_timeout=self.ping_timeout,\n                max_message_size=self.max_message_size,\n                compression_options=self.get_compression_options(),\n            )\n            return WebSocketProtocol13(self, False, params)\n        return None\n\n    def _detach_stream(self) -> IOStream:\n        # disable non-WS methods\n        for method in [\n            \"write\",\n            \"redirect\",\n            \"set_header\",\n            \"set_cookie\",\n            \"set_status\",\n            \"flush\",\n            \"finish\",\n        ]:\n            setattr(self, method, _raise_not_supported_for_websockets)\n        return self.detach()\n\n\ndef _raise_not_supported_for_websockets(*args: Any, **kwargs: Any) -> None:\n    raise RuntimeError(\"Method not supported for Web Sockets\")\n\n\nclass WebSocketProtocol(abc.ABC):\n    \"\"\"Base class for WebSocket protocol versions.\n    \"\"\"\n\n    def __init__(self, handler: \"_WebSocketDelegate\") -> None:\n        self.handler = handler\n        self.stream = None  # type: Optional[IOStream]\n        self.client_terminated = False\n        self.server_terminated = False\n\n    def _run_callback(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> \"Optional[Future[Any]]\":\n        \"\"\"Runs the given callback with exception handling.\n\n        If the callback is a coroutine, returns its Future. On error, aborts the\n        websocket connection and returns None.\n        \"\"\"\n        try:\n            result = callback(*args, **kwargs)\n        except Exception:\n            self.handler.log_exception(*sys.exc_info())\n            self._abort()\n            return None\n        else:\n            if result is not None:\n                result = gen.convert_yielded(result)\n                assert self.stream is not None\n                self.stream.io_loop.add_future(result, lambda f: f.result())\n            return result\n\n    def on_connection_close(self) -> None:\n        self._abort()\n\n    def _abort(self) -> None:\n        \"\"\"Instantly aborts the WebSocket connection by closing the socket\"\"\"\n        self.client_terminated = True\n        self.server_terminated = True\n        if self.stream is not None:\n            self.stream.close()  # forcibly tear down the connection\n        self.close()  # let the subclass cleanup\n\n    @abc.abstractmethod\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def is_closing(self) -> bool:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        raise NotImplementedError()\n\n    @property\n    @abc.abstractmethod\n    def selected_subprotocol(self) -> Optional[str]:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_ping(self, data: bytes) -> None:\n        raise NotImplementedError()\n\n    # The entry points below are used by WebSocketClientConnection,\n    # which was introduced after we only supported a single version of\n    # WebSocketProtocol. The WebSocketProtocol/WebSocketProtocol13\n    # boundary is currently pretty ad-hoc.\n    @abc.abstractmethod\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def start_pinging(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def _receive_frame_loop(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def set_nodelay(self, x: bool) -> None:\n        raise NotImplementedError()\n\n\nclass _PerMessageDeflateCompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        # There is no symbolic constant for the minimum wbits value.\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n\n        if (\n            compression_options is None\n            or \"compression_level\" not in compression_options\n        ):\n            self._compression_level = tornado.web.GZipContentEncoding.GZIP_LEVEL\n        else:\n            self._compression_level = compression_options[\"compression_level\"]\n\n        if compression_options is None or \"mem_level\" not in compression_options:\n            self._mem_level = 8\n        else:\n            self._mem_level = compression_options[\"mem_level\"]\n\n        if persistent:\n            self._compressor = self._create_compressor()  # type: Optional[_Compressor]\n        else:\n            self._compressor = None\n\n    def _create_compressor(self) -> \"_Compressor\":\n        return zlib.compressobj(\n            self._compression_level, zlib.DEFLATED, -self._max_wbits, self._mem_level\n        )\n\n    def compress(self, data: bytes) -> bytes:\n        compressor = self._compressor or self._create_compressor()\n        data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)\n        assert data.endswith(b\"\\x00\\x00\\xff\\xff\")\n        return data[:-4]\n\n\nclass _PerMessageDeflateDecompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        max_message_size: int,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self._max_message_size = max_message_size\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n        if persistent:\n            self._decompressor = (\n                self._create_decompressor()\n            )  # type: Optional[_Decompressor]\n        else:\n            self._decompressor = None\n\n    def _create_decompressor(self) -> \"_Decompressor\":\n        return zlib.decompressobj(-self._max_wbits)\n\n    def decompress(self, data: bytes) -> bytes:\n        decompressor = self._decompressor or self._create_decompressor()\n        result = decompressor.decompress(\n            data + b\"\\x00\\x00\\xff\\xff\", self._max_message_size\n        )\n        if decompressor.unconsumed_tail:\n            raise _DecompressTooLargeError()\n        return result\n\n\nclass WebSocketProtocol13(WebSocketProtocol):\n    \"\"\"Implementation of the WebSocket protocol from RFC 6455.\n\n    This class supports versions 7 and 8 of the protocol in addition to the\n    final version 13.\n    \"\"\"\n\n    # Bit masks for the first byte of a frame.\n    FIN = 0x80\n    RSV1 = 0x40\n    RSV2 = 0x20\n    RSV3 = 0x10\n    RSV_MASK = RSV1 | RSV2 | RSV3\n    OPCODE_MASK = 0x0F\n\n    stream = None  # type: IOStream\n\n    def __init__(\n        self,\n        handler: \"_WebSocketDelegate\",\n        mask_outgoing: bool,\n        params: _WebSocketParams,\n    ) -> None:\n        WebSocketProtocol.__init__(self, handler)\n        self.mask_outgoing = mask_outgoing\n        self.params = params\n        self._final_frame = False\n        self._frame_opcode = None\n        self._masked_frame = None\n        self._frame_mask = None  # type: Optional[bytes]\n        self._frame_length = None\n        self._fragmented_message_buffer = None  # type: Optional[bytes]\n        self._fragmented_message_opcode = None\n        self._waiting = None  # type: object\n        self._compression_options = params.compression_options\n        self._decompressor = None  # type: Optional[_PerMessageDeflateDecompressor]\n        self._compressor = None  # type: Optional[_PerMessageDeflateCompressor]\n        self._frame_compressed = None  # type: Optional[bool]\n        # The total uncompressed size of all messages received or sent.\n        # Unicode messages are encoded to utf8.\n        # Only for testing; subject to change.\n        self._message_bytes_in = 0\n        self._message_bytes_out = 0\n        # The total size of all packets received or sent.  Includes\n        # the effect of compression, frame overhead, and control frames.\n        self._wire_bytes_in = 0\n        self._wire_bytes_out = 0\n        self.ping_callback = None  # type: Optional[PeriodicCallback]\n        self.last_ping = 0.0\n        self.last_pong = 0.0\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n\n    # Use a property for this to satisfy the abc.\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        return self._selected_subprotocol\n\n    @selected_subprotocol.setter\n    def selected_subprotocol(self, value: Optional[str]) -> None:\n        self._selected_subprotocol = value\n\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        try:\n            self._handle_websocket_headers(handler)\n        except ValueError:\n            handler.set_status(400)\n            log_msg = \"Missing/Invalid WebSocket headers\"\n            handler.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        try:\n            await self._accept_connection(handler)\n        except asyncio.CancelledError:\n            self._abort()\n            return\n        except ValueError:\n            gen_log.debug(\"Malformed WebSocket request received\", exc_info=True)\n            self._abort()\n            return\n\n    def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:\n        \"\"\"Verifies all invariant- and required headers\n\n        If a header is missing or have an incorrect value ValueError will be\n        raised\n        \"\"\"\n        fields = (\"Host\", \"Sec-Websocket-Key\", \"Sec-Websocket-Version\")\n        if not all(map(lambda f: handler.request.headers.get(f), fields)):\n            raise ValueError(\"Missing/Invalid WebSocket headers\")\n\n    @staticmethod\n    def compute_accept_value(key: Union[str, bytes]) -> str:\n        \"\"\"Computes the value for the Sec-WebSocket-Accept header,\n        given the value for Sec-WebSocket-Key.\n        \"\"\"\n        sha1 = hashlib.sha1()\n        sha1.update(utf8(key))\n        sha1.update(b\"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\")  # Magic value\n        return native_str(base64.b64encode(sha1.digest()))\n\n    def _challenge_response(self, handler: WebSocketHandler) -> str:\n        return WebSocketProtocol13.compute_accept_value(\n            cast(str, handler.request.headers.get(\"Sec-Websocket-Key\"))\n        )\n\n    async def _accept_connection(self, handler: WebSocketHandler) -> None:\n        subprotocol_header = handler.request.headers.get(\"Sec-WebSocket-Protocol\")\n        if subprotocol_header:\n            subprotocols = [s.strip() for s in subprotocol_header.split(\",\")]\n        else:\n            subprotocols = []\n        self.selected_subprotocol = handler.select_subprotocol(subprotocols)\n        if self.selected_subprotocol:\n            assert self.selected_subprotocol in subprotocols\n            handler.set_header(\"Sec-WebSocket-Protocol\", self.selected_subprotocol)\n\n        extensions = self._parse_extensions_header(handler.request.headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                # TODO: negotiate parameters if compression_options\n                # specifies limits.\n                self._create_compressors(\"server\", ext[1], self._compression_options)\n                if (\n                    \"client_max_window_bits\" in ext[1]\n                    and ext[1][\"client_max_window_bits\"] is None\n                ):\n                    # Don't echo an offered client_max_window_bits\n                    # parameter with no value.\n                    del ext[1][\"client_max_window_bits\"]\n                handler.set_header(\n                    \"Sec-WebSocket-Extensions\",\n                    httputil._encode_header(\"permessage-deflate\", ext[1]),\n                )\n                break\n\n        handler.clear_header(\"Content-Type\")\n        handler.set_status(101)\n        handler.set_header(\"Upgrade\", \"websocket\")\n        handler.set_header(\"Connection\", \"Upgrade\")\n        handler.set_header(\"Sec-WebSocket-Accept\", self._challenge_response(handler))\n        handler.finish()\n\n        self.stream = handler._detach_stream()\n\n        self.start_pinging()\n        try:\n            open_result = handler.open(*handler.open_args, **handler.open_kwargs)\n            if open_result is not None:\n                await open_result\n        except Exception:\n            handler.log_exception(*sys.exc_info())\n            self._abort()\n            return\n\n        await self._receive_frame_loop()\n\n    def _parse_extensions_header(\n        self, headers: httputil.HTTPHeaders\n    ) -> List[Tuple[str, Dict[str, str]]]:\n        extensions = headers.get(\"Sec-WebSocket-Extensions\", \"\")\n        if extensions:\n            return [httputil._parse_header(e.strip()) for e in extensions.split(\",\")]\n        return []\n\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        \"\"\"Process the headers sent by the server to this client connection.\n\n        'key' is the websocket handshake challenge/response key.\n        \"\"\"\n        assert headers[\"Upgrade\"].lower() == \"websocket\"\n        assert headers[\"Connection\"].lower() == \"upgrade\"\n        accept = self.compute_accept_value(key)\n        assert headers[\"Sec-Websocket-Accept\"] == accept\n\n        extensions = self._parse_extensions_header(headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                self._create_compressors(\"client\", ext[1])\n            else:\n                raise ValueError(\"unsupported extension %r\", ext)\n\n        self.selected_subprotocol = headers.get(\"Sec-WebSocket-Protocol\", None)\n\n    def _get_compressor_options(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Converts a websocket agreed_parameters set to keyword arguments\n        for our compressor objects.\n        \"\"\"\n        options = dict(\n            persistent=(side + \"_no_context_takeover\") not in agreed_parameters\n        )  # type: Dict[str, Any]\n        wbits_header = agreed_parameters.get(side + \"_max_window_bits\", None)\n        if wbits_header is None:\n            options[\"max_wbits\"] = zlib.MAX_WBITS\n        else:\n            options[\"max_wbits\"] = int(wbits_header)\n        options[\"compression_options\"] = compression_options\n        return options\n\n    def _create_compressors(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        # TODO: handle invalid parameters gracefully\n        allowed_keys = set(\n            [\n                \"server_no_context_takeover\",\n                \"client_no_context_takeover\",\n                \"server_max_window_bits\",\n                \"client_max_window_bits\",\n            ]\n        )\n        for key in agreed_parameters:\n            if key not in allowed_keys:\n                raise ValueError(\"unsupported compression parameter %r\" % key)\n        other_side = \"client\" if (side == \"server\") else \"server\"\n        self._compressor = _PerMessageDeflateCompressor(\n            **self._get_compressor_options(side, agreed_parameters, compression_options)\n        )\n        self._decompressor = _PerMessageDeflateDecompressor(\n            max_message_size=self.params.max_message_size,\n            **self._get_compressor_options(\n                other_side, agreed_parameters, compression_options\n            )\n        )\n\n    def _write_frame(\n        self, fin: bool, opcode: int, data: bytes, flags: int = 0\n    ) -> \"Future[None]\":\n        data_len = len(data)\n        if opcode & 0x8:\n            # All control frames MUST have a payload length of 125\n            # bytes or less and MUST NOT be fragmented.\n            if not fin:\n                raise ValueError(\"control frames may not be fragmented\")\n            if data_len > 125:\n                raise ValueError(\"control frame payloads may not exceed 125 bytes\")\n        if fin:\n            finbit = self.FIN\n        else:\n            finbit = 0\n        frame = struct.pack(\"B\", finbit | opcode | flags)\n        if self.mask_outgoing:\n            mask_bit = 0x80\n        else:\n            mask_bit = 0\n        if data_len < 126:\n            frame += struct.pack(\"B\", data_len | mask_bit)\n        elif data_len <= 0xFFFF:\n            frame += struct.pack(\"!BH\", 126 | mask_bit, data_len)\n        else:\n            frame += struct.pack(\"!BQ\", 127 | mask_bit, data_len)\n        if self.mask_outgoing:\n            mask = os.urandom(4)\n            data = mask + _websocket_mask(mask, data)\n        frame += data\n        self._wire_bytes_out += len(frame)\n        return self.stream.write(frame)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\"\"\"\n        if binary:\n            opcode = 0x2\n        else:\n            opcode = 0x1\n        message = tornado.escape.utf8(message)\n        assert isinstance(message, bytes)\n        self._message_bytes_out += len(message)\n        flags = 0\n        if self._compressor:\n            message = self._compressor.compress(message)\n            flags |= self.RSV1\n        # For historical reasons, write methods in Tornado operate in a semi-synchronous\n        # mode in which awaiting the Future they return is optional (But errors can\n        # still be raised). This requires us to go through an awkward dance here\n        # to transform the errors that may be returned while presenting the same\n        # semi-synchronous interface.\n        try:\n            fut = self._write_frame(True, opcode, message, flags=flags)\n        except StreamClosedError:\n            raise WebSocketClosedError()\n\n        async def wrapper() -> None:\n            try:\n                await fut\n            except StreamClosedError:\n                raise WebSocketClosedError()\n\n        return asyncio.ensure_future(wrapper())\n\n    def write_ping(self, data: bytes) -> None:\n        \"\"\"Send ping frame.\"\"\"\n        assert isinstance(data, bytes)\n        self._write_frame(True, 0x9, data)\n\n    async def _receive_frame_loop(self) -> None:\n        try:\n            while not self.client_terminated:\n                await self._receive_frame()\n        except StreamClosedError:\n            self._abort()\n        self.handler.on_ws_connection_close(self.close_code, self.close_reason)\n\n    async def _read_bytes(self, n: int) -> bytes:\n        data = await self.stream.read_bytes(n)\n        self._wire_bytes_in += n\n        return data\n\n    async def _receive_frame(self) -> None:\n        # Read the frame header.\n        data = await self._read_bytes(2)\n        header, mask_payloadlen = struct.unpack(\"BB\", data)\n        is_final_frame = header & self.FIN\n        reserved_bits = header & self.RSV_MASK\n        opcode = header & self.OPCODE_MASK\n        opcode_is_control = opcode & 0x8\n        if self._decompressor is not None and opcode != 0:\n            # Compression flag is present in the first frame's header,\n            # but we can't decompress until we have all the frames of\n            # the message.\n            self._frame_compressed = bool(reserved_bits & self.RSV1)\n            reserved_bits &= ~self.RSV1\n        if reserved_bits:\n            # client is using as-yet-undefined extensions; abort\n            self._abort()\n            return\n        is_masked = bool(mask_payloadlen & 0x80)\n        payloadlen = mask_payloadlen & 0x7F\n\n        # Parse and validate the length.\n        if opcode_is_control and payloadlen >= 126:\n            # control frames must have payload < 126\n            self._abort()\n            return\n        if payloadlen < 126:\n            self._frame_length = payloadlen\n        elif payloadlen == 126:\n            data = await self._read_bytes(2)\n            payloadlen = struct.unpack(\"!H\", data)[0]\n        elif payloadlen == 127:\n            data = await self._read_bytes(8)\n            payloadlen = struct.unpack(\"!Q\", data)[0]\n        new_len = payloadlen\n        if self._fragmented_message_buffer is not None:\n            new_len += len(self._fragmented_message_buffer)\n        if new_len > self.params.max_message_size:\n            self.close(1009, \"message too big\")\n            self._abort()\n            return\n\n        # Read the payload, unmasking if necessary.\n        if is_masked:\n            self._frame_mask = await self._read_bytes(4)\n        data = await self._read_bytes(payloadlen)\n        if is_masked:\n            assert self._frame_mask is not None\n            data = _websocket_mask(self._frame_mask, data)\n\n        # Decide what to do with this frame.\n        if opcode_is_control:\n            # control frames may be interleaved with a series of fragmented\n            # data frames, so control frames must not interact with\n            # self._fragmented_*\n            if not is_final_frame:\n                # control frames must not be fragmented\n                self._abort()\n                return\n        elif opcode == 0:  # continuation frame\n            if self._fragmented_message_buffer is None:\n                # nothing to continue\n                self._abort()\n                return\n            self._fragmented_message_buffer += data\n            if is_final_frame:\n                opcode = self._fragmented_message_opcode\n                data = self._fragmented_message_buffer\n                self._fragmented_message_buffer = None\n        else:  # start of new data message\n            if self._fragmented_message_buffer is not None:\n                # can't start new message until the old one is finished\n                self._abort()\n                return\n            if not is_final_frame:\n                self._fragmented_message_opcode = opcode\n                self._fragmented_message_buffer = data\n\n        if is_final_frame:\n            handled_future = self._handle_message(opcode, data)\n            if handled_future is not None:\n                await handled_future\n\n    def _handle_message(self, opcode: int, data: bytes) -> \"Optional[Future[None]]\":\n        \"\"\"Execute on_message, returning its Future if it is a coroutine.\"\"\"\n        if self.client_terminated:\n            return None\n\n        if self._frame_compressed:\n            assert self._decompressor is not None\n            try:\n                data = self._decompressor.decompress(data)\n            except _DecompressTooLargeError:\n                self.close(1009, \"message too big after decompression\")\n                self._abort()\n                return None\n\n        if opcode == 0x1:\n            # UTF-8 data\n            self._message_bytes_in += len(data)\n            try:\n                decoded = data.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                self._abort()\n                return None\n            return self._run_callback(self.handler.on_message, decoded)\n        elif opcode == 0x2:\n            # Binary data\n            self._message_bytes_in += len(data)\n            return self._run_callback(self.handler.on_message, data)\n        elif opcode == 0x8:\n            # Close\n            self.client_terminated = True\n            if len(data) >= 2:\n                self.close_code = struct.unpack(\">H\", data[:2])[0]\n            if len(data) > 2:\n                self.close_reason = to_unicode(data[2:])\n            # Echo the received close code, if any (RFC 6455 section 5.5.1).\n            self.close(self.close_code)\n        elif opcode == 0x9:\n            # Ping\n            try:\n                self._write_frame(True, 0xA, data)\n            except StreamClosedError:\n                self._abort()\n            self._run_callback(self.handler.on_ping, data)\n        elif opcode == 0xA:\n            # Pong\n            self.last_pong = IOLoop.current().time()\n            return self._run_callback(self.handler.on_pong, data)\n        else:\n            self._abort()\n        return None\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the WebSocket connection.\"\"\"\n        if not self.server_terminated:\n            if not self.stream.closed():\n                if code is None and reason is not None:\n                    code = 1000  # \"normal closure\" status code\n                if code is None:\n                    close_data = b\"\"\n                else:\n                    close_data = struct.pack(\">H\", code)\n                if reason is not None:\n                    close_data += utf8(reason)\n                try:\n                    self._write_frame(True, 0x8, close_data)\n                except StreamClosedError:\n                    self._abort()\n            self.server_terminated = True\n        if self.client_terminated:\n            if self._waiting is not None:\n                self.stream.io_loop.remove_timeout(self._waiting)\n                self._waiting = None\n            self.stream.close()\n        elif self._waiting is None:\n            # Give the client a few seconds to complete a clean shutdown,\n            # otherwise just close the connection.\n            self._waiting = self.stream.io_loop.add_timeout(\n                self.stream.io_loop.time() + 5, self._abort\n            )\n        if self.ping_callback:\n            self.ping_callback.stop()\n            self.ping_callback = None\n\n    def is_closing(self) -> bool:\n        \"\"\"Return ``True`` if this connection is closing.\n\n        The connection is considered closing if either side has\n        initiated its closing handshake or if the stream has been\n        shut down uncleanly.\n        \"\"\"\n        return self.stream.closed() or self.client_terminated or self.server_terminated\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        interval = self.params.ping_interval\n        if interval is not None:\n            return interval\n        return 0\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        timeout = self.params.ping_timeout\n        if timeout is not None:\n            return timeout\n        assert self.ping_interval is not None\n        return max(3 * self.ping_interval, 30)\n\n    def start_pinging(self) -> None:\n        \"\"\"Start sending periodic pings to keep the connection alive\"\"\"\n        assert self.ping_interval is not None\n        if self.ping_interval > 0:\n            self.last_ping = self.last_pong = IOLoop.current().time()\n            self.ping_callback = PeriodicCallback(\n                self.periodic_ping, self.ping_interval * 1000\n            )\n            self.ping_callback.start()\n\n    def periodic_ping(self) -> None:\n        \"\"\"Send a ping to keep the websocket alive\n\n        Called periodically if the websocket_ping_interval is set and non-zero.\n        \"\"\"\n        if self.is_closing() and self.ping_callback is not None:\n            self.ping_callback.stop()\n            return\n\n        # Check for timeout on pong. Make sure that we really have\n        # sent a recent ping in case the machine with both server and\n        # client has been suspended since the last ping.\n        now = IOLoop.current().time()\n        since_last_pong = now - self.last_pong\n        since_last_ping = now - self.last_ping\n        assert self.ping_interval is not None\n        assert self.ping_timeout is not None\n        if (\n            since_last_ping < 2 * self.ping_interval\n            and since_last_pong > self.ping_timeout\n        ):\n            self.close()\n            return\n\n        self.write_ping(b\"\")\n        self.last_ping = now\n\n    def set_nodelay(self, x: bool) -> None:\n        self.stream.set_nodelay(x)\n\n\nclass WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        # Websocket connection is currently unable to follow redirects\n        request.follow_redirects = False\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))\n\n\ndef websocket_connect(\n    url: Union[str, httpclient.HTTPRequest],\n    callback: Optional[Callable[[\"Future[WebSocketClientConnection]\"], None]] = None,\n    connect_timeout: Optional[float] = None,\n    on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n    compression_options: Optional[Dict[str, Any]] = None,\n    ping_interval: Optional[float] = None,\n    ping_timeout: Optional[float] = None,\n    max_message_size: int = _default_max_message_size,\n    subprotocols: Optional[List[str]] = None,\n) -> \"Awaitable[WebSocketClientConnection]\":\n    \"\"\"Client-side websocket support.\n\n    Takes a url and returns a Future whose result is a\n    `WebSocketClientConnection`.\n\n    ``compression_options`` is interpreted in the same way as the\n    return value of `.WebSocketHandler.get_compression_options`.\n\n    The connection supports two styles of operation. In the coroutine\n    style, the application typically calls\n    `~.WebSocketClientConnection.read_message` in a loop::\n\n        conn = yield websocket_connect(url)\n        while True:\n            msg = yield conn.read_message()\n            if msg is None: break\n            # Do something with msg\n\n    In the callback style, pass an ``on_message_callback`` to\n    ``websocket_connect``. In both styles, a message of ``None``\n    indicates that the connection has been closed.\n\n    ``subprotocols`` may be a list of strings specifying proposed\n    subprotocols. The selected protocol may be found on the\n    ``selected_subprotocol`` attribute of the connection object\n    when the connection is complete.\n\n    .. versionchanged:: 3.2\n       Also accepts ``HTTPRequest`` objects in place of urls.\n\n    .. versionchanged:: 4.1\n       Added ``compression_options`` and ``on_message_callback``.\n\n    .. versionchanged:: 4.5\n       Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size``\n       arguments, which have the same meaning as in `WebSocketHandler`.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       Added the ``subprotocols`` argument.\n    \"\"\"\n    if isinstance(url, httpclient.HTTPRequest):\n        assert connect_timeout is None\n        request = url\n        # Copy and convert the headers dict/object (see comments in\n        # AsyncHTTPClient.fetch)\n        request.headers = httputil.HTTPHeaders(request.headers)\n    else:\n        request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)\n    request = cast(\n        httpclient.HTTPRequest,\n        httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS),\n    )\n    conn = WebSocketClientConnection(\n        request,\n        on_message_callback=on_message_callback,\n        compression_options=compression_options,\n        ping_interval=ping_interval,\n        ping_timeout=ping_timeout,\n        max_message_size=max_message_size,\n        subprotocols=subprotocols,\n    )\n    if callback is not None:\n        IOLoop.current().add_future(conn.connect_future, callback)\n    return conn.connect_future\n",
            "header": {
                "file": {
                    "path": "tornado/websocket.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "ff0c2416",
                "new_commit_hash": "eef49e7c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/websocket.py"
            },
            "plus_file": {
                "path": "b/tornado/websocket.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 1409,
                            "length": 6
                        },
                        "new_range": {
                            "start": 1409,
                            "length": 9
                        },
                        "section": "class WebSocketClientConnection(simple_httpclient._HTTPConnection):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "                \"Sec-WebSocket-Extensions\"",
                                "type": "context"
                            },
                            {
                                "content": "            ] = \"permessage-deflate; client_max_window_bits\"",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "        # Websocket connection is currently unable to follow redirects",
                                "type": "added"
                            },
                            {
                                "content": "        request.follow_redirects = False",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.tcp_client = TCPClient()",
                                "type": "context"
                            },
                            {
                                "content": "        super().__init__(",
                                "type": "context"
                            },
                            {
                                "content": "            None,",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/websocket.py",
                            "type": "class",
                            "name": "WebSocketClientConnection",
                            "content": "class WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        # Websocket connection is currently unable to follow redirects\n        request.follow_redirects = False\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1357,
                            "end_lineno": 1586,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/websocket.py",
                            "type": "method",
                            "name": "WebSocketClientConnection.__init__",
                            "content": "class WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        # Websocket connection is currently unable to follow redirects\n        request.follow_redirects = False\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 1366,
                            "end_lineno": 1425,
                            "parent": {
                                "file_name": "tornado/websocket.py",
                                "type": "class",
                                "name": "WebSocketClientConnection",
                                "content": "class WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        # Websocket connection is currently unable to follow redirects\n        request.follow_redirects = False\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 1357,
                                "end_lineno": 1586,
                                "parent": null
                            }
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "5a069a8820e456bf886717898e9c21ead20289a5^",
    "new_commit_hash": "5a069a8820e456bf886717898e9c21ead20289a5",
    "commit_message": "Merge pull request #2920 from ploxiln/websocket_no_redirect\n\nwebsocket: set follow_redirects to False",
    "commit_date": "2020-09-25T15:18:38-04:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "5a069a8820e456bf886717898e9c21ead20289a5",
    "test_file_codes": [
        "import asyncio\nimport functools\nimport traceback\nimport typing\nimport unittest\n\nfrom tornado.concurrent import Future\nfrom tornado import gen\nfrom tornado.httpclient import HTTPError, HTTPRequest\nfrom tornado.locks import Event\nfrom tornado.log import gen_log, app_log\nfrom tornado.simple_httpclient import SimpleAsyncHTTPClient\nfrom tornado.template import DictLoader\nfrom tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog\nfrom tornado.web import Application, RequestHandler\n\ntry:\n    import tornado.websocket  # noqa: F401\n    from tornado.util import _websocket_mask_python\nexcept ImportError:\n    # The unittest module presents misleading errors on ImportError\n    # (it acts as if websocket_test could not be found, hiding the underlying\n    # error).  If we get an ImportError here (which could happen due to\n    # TORNADO_EXTENSION=1), print some extra information before failing.\n    traceback.print_exc()\n    raise\n\nfrom tornado.websocket import (\n    WebSocketHandler,\n    websocket_connect,\n    WebSocketError,\n    WebSocketClosedError,\n)\n\ntry:\n    from tornado import speedups\nexcept ImportError:\n    speedups = None  # type: ignore\n\n\nclass TestWebSocketHandler(WebSocketHandler):\n    \"\"\"Base class for testing handlers that exposes the on_close event.\n\n    This allows for tests to see the close code and reason on the\n    server side.\n\n    \"\"\"\n\n    def initialize(self, close_future=None, compression_options=None):\n        self.close_future = close_future\n        self.compression_options = compression_options\n\n    def get_compression_options(self):\n        return self.compression_options\n\n    def on_close(self):\n        if self.close_future is not None:\n            self.close_future.set_result((self.close_code, self.close_reason))\n\n\nclass EchoHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def on_message(self, message):\n        try:\n            yield self.write_message(message, isinstance(message, bytes))\n        except asyncio.CancelledError:\n            pass\n        except WebSocketClosedError:\n            pass\n\n\nclass ErrorInOnMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        1 / 0\n\n\nclass HeaderHandler(TestWebSocketHandler):\n    def open(self):\n        methods_to_test = [\n            functools.partial(self.write, \"This should not work\"),\n            functools.partial(self.redirect, \"http://localhost/elsewhere\"),\n            functools.partial(self.set_header, \"X-Test\", \"\"),\n            functools.partial(self.set_cookie, \"Chocolate\", \"Chip\"),\n            functools.partial(self.set_status, 503),\n            self.flush,\n            self.finish,\n        ]\n        for method in methods_to_test:\n            try:\n                # In a websocket context, many RequestHandler methods\n                # raise RuntimeErrors.\n                method()  # type: ignore\n                raise Exception(\"did not get expected exception\")\n            except RuntimeError:\n                pass\n        self.write_message(self.request.headers.get(\"X-Test\", \"\"))\n\n\nclass HeaderEchoHandler(TestWebSocketHandler):\n    def set_default_headers(self):\n        self.set_header(\"X-Extra-Response-Header\", \"Extra-Response-Value\")\n\n    def prepare(self):\n        for k, v in self.request.headers.get_all():\n            if k.lower().startswith(\"x-test\"):\n                self.set_header(k, v)\n\n\nclass NonWebSocketHandler(RequestHandler):\n    def get(self):\n        self.write(\"ok\")\n\n\nclass RedirectHandler(RequestHandler):\n    def get(self):\n        self.redirect(\"/echo\")\n\n\nclass CloseReasonHandler(TestWebSocketHandler):\n    def open(self):\n        self.on_close_called = False\n        self.close(1001, \"goodbye\")\n\n\nclass AsyncPrepareHandler(TestWebSocketHandler):\n    @gen.coroutine\n    def prepare(self):\n        yield gen.moment\n\n    def on_message(self, message):\n        self.write_message(message)\n\n\nclass PathArgsHandler(TestWebSocketHandler):\n    def open(self, arg):\n        self.write_message(arg)\n\n\nclass CoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    @gen.coroutine\n    def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        yield gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass RenderMessageHandler(TestWebSocketHandler):\n    def on_message(self, message):\n        self.write_message(self.render_string(\"message.html\", message=message))\n\n\nclass SubprotocolHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.select_subprotocol_called = False\n\n    def select_subprotocol(self, subprotocols):\n        if self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol called twice\")\n        self.select_subprotocol_called = True\n        if \"goodproto\" in subprotocols:\n            return \"goodproto\"\n        return None\n\n    def open(self):\n        if not self.select_subprotocol_called:\n            raise Exception(\"select_subprotocol not called\")\n        self.write_message(\"subprotocol=%s\" % self.selected_subprotocol)\n\n\nclass OpenCoroutineHandler(TestWebSocketHandler):\n    def initialize(self, test, **kwargs):\n        super().initialize(**kwargs)\n        self.test = test\n        self.open_finished = False\n\n    @gen.coroutine\n    def open(self):\n        yield self.test.message_sent.wait()\n        yield gen.sleep(0.010)\n        self.open_finished = True\n\n    def on_message(self, message):\n        if not self.open_finished:\n            raise Exception(\"on_message called before open finished\")\n        self.write_message(\"ok\")\n\n\nclass ErrorInOpenHandler(TestWebSocketHandler):\n    def open(self):\n        raise Exception(\"boom\")\n\n\nclass ErrorInAsyncOpenHandler(TestWebSocketHandler):\n    async def open(self):\n        await asyncio.sleep(0)\n        raise Exception(\"boom\")\n\n\nclass NoDelayHandler(TestWebSocketHandler):\n    def open(self):\n        self.set_nodelay(True)\n        self.write_message(\"hello\")\n\n\nclass WebSocketBaseTestCase(AsyncHTTPTestCase):\n    @gen.coroutine\n    def ws_connect(self, path, **kwargs):\n        ws = yield websocket_connect(\n            \"ws://127.0.0.1:%d%s\" % (self.get_http_port(), path), **kwargs\n        )\n        raise gen.Return(ws)\n\n\nclass WebSocketTest(WebSocketBaseTestCase):\n    def get_app(self):\n        self.close_future = Future()  # type: Future[None]\n        return Application(\n            [\n                (\"/echo\", EchoHandler, dict(close_future=self.close_future)),\n                (\"/non_ws\", NonWebSocketHandler),\n                (\"/redirect\", RedirectHandler),\n                (\"/header\", HeaderHandler, dict(close_future=self.close_future)),\n                (\n                    \"/header_echo\",\n                    HeaderEchoHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/close_reason\",\n                    CloseReasonHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/error_in_on_message\",\n                    ErrorInOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/async_prepare\",\n                    AsyncPrepareHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/path_args/(.*)\",\n                    PathArgsHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/coroutine\",\n                    CoroutineOnMessageHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\"/render\", RenderMessageHandler, dict(close_future=self.close_future)),\n                (\n                    \"/subprotocol\",\n                    SubprotocolHandler,\n                    dict(close_future=self.close_future),\n                ),\n                (\n                    \"/open_coroutine\",\n                    OpenCoroutineHandler,\n                    dict(close_future=self.close_future, test=self),\n                ),\n                (\"/error_in_open\", ErrorInOpenHandler),\n                (\"/error_in_async_open\", ErrorInAsyncOpenHandler),\n                (\"/nodelay\", NoDelayHandler),\n            ],\n            template_loader=DictLoader({\"message.html\": \"<b>{{ message }}</b>\"}),\n        )\n\n    def get_http_client(self):\n        # These tests require HTTP/1; force the use of SimpleAsyncHTTPClient.\n        return SimpleAsyncHTTPClient()\n\n    def tearDown(self):\n        super().tearDown()\n        RequestHandler._template_loaders.clear()\n\n    def test_http_request(self):\n        # WS server, HTTP client.\n        response = self.fetch(\"/echo\")\n        self.assertEqual(response.code, 400)\n\n    def test_missing_websocket_key(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"13\",\n            },\n        )\n        self.assertEqual(response.code, 400)\n\n    def test_bad_websocket_version(self):\n        response = self.fetch(\n            \"/echo\",\n            headers={\n                \"Connection\": \"Upgrade\",\n                \"Upgrade\": \"WebSocket\",\n                \"Sec-WebSocket-Version\": \"12\",\n            },\n        )\n        self.assertEqual(response.code, 426)\n\n    @gen_test\n    def test_websocket_gen(self):\n        ws = yield self.ws_connect(\"/echo\")\n        yield ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    def test_websocket_callbacks(self):\n        websocket_connect(\n            \"ws://127.0.0.1:%d/echo\" % self.get_http_port(), callback=self.stop\n        )\n        ws = self.wait().result()\n        ws.write_message(\"hello\")\n        ws.read_message(self.stop)\n        response = self.wait().result()\n        self.assertEqual(response, \"hello\")\n        self.close_future.add_done_callback(lambda f: self.stop())\n        ws.close()\n        self.wait()\n\n    @gen_test\n    def test_binary_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(b\"hello \\xe9\", binary=True)\n        response = yield ws.read_message()\n        self.assertEqual(response, b\"hello \\xe9\")\n\n    @gen_test\n    def test_unicode_message(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.write_message(u\"hello \\u00e9\")\n        response = yield ws.read_message()\n        self.assertEqual(response, u\"hello \\u00e9\")\n\n    @gen_test\n    def test_render_message(self):\n        ws = yield self.ws_connect(\"/render\")\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"<b>hello</b>\")\n\n    @gen_test\n    def test_error_in_on_message(self):\n        ws = yield self.ws_connect(\"/error_in_on_message\")\n        ws.write_message(\"hello\")\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            response = yield ws.read_message()\n        self.assertIs(response, None)\n\n    @gen_test\n    def test_websocket_http_fail(self):\n        with self.assertRaises(HTTPError) as cm:\n            yield self.ws_connect(\"/notfound\")\n        self.assertEqual(cm.exception.code, 404)\n\n    @gen_test\n    def test_websocket_http_success(self):\n        with self.assertRaises(WebSocketError):\n            yield self.ws_connect(\"/non_ws\")\n\n    @gen_test\n    def test_websocket_http_redirect(self):\n        with self.assertRaises(HTTPError):\n            yield self.ws_connect(\"/redirect\")\n\n    @gen_test\n    def test_websocket_network_fail(self):\n        sock, port = bind_unused_port()\n        sock.close()\n        with self.assertRaises(IOError):\n            with ExpectLog(gen_log, \".*\"):\n                yield websocket_connect(\n                    \"ws://127.0.0.1:%d/\" % port, connect_timeout=3600\n                )\n\n    @gen_test\n    def test_websocket_close_buffered_data(self):\n        ws = yield websocket_connect(\"ws://127.0.0.1:%d/echo\" % self.get_http_port())\n        ws.write_message(\"hello\")\n        ws.write_message(\"world\")\n        # Close the underlying stream.\n        ws.stream.close()\n\n    @gen_test\n    def test_websocket_headers(self):\n        # Ensure that arbitrary headers can be passed through websocket_connect.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header\" % self.get_http_port(),\n                headers={\"X-Test\": \"hello\"},\n            )\n        )\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_websocket_header_echo(self):\n        # Ensure that headers can be returned in the response.\n        # Specifically, that arbitrary headers passed through websocket_connect\n        # can be returned.\n        ws = yield websocket_connect(\n            HTTPRequest(\n                \"ws://127.0.0.1:%d/header_echo\" % self.get_http_port(),\n                headers={\"X-Test-Hello\": \"hello\"},\n            )\n        )\n        self.assertEqual(ws.headers.get(\"X-Test-Hello\"), \"hello\")\n        self.assertEqual(\n            ws.headers.get(\"X-Extra-Response-Header\"), \"Extra-Response-Value\"\n        )\n\n    @gen_test\n    def test_server_close_reason(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(msg, None)\n        self.assertEqual(ws.close_code, 1001)\n        self.assertEqual(ws.close_reason, \"goodbye\")\n        # The on_close callback is called no matter which side closed.\n        code, reason = yield self.close_future\n        # The client echoed the close code it received to the server,\n        # so the server's close code (returned via close_future) is\n        # the same.\n        self.assertEqual(code, 1001)\n\n    @gen_test\n    def test_client_close_reason(self):\n        ws = yield self.ws_connect(\"/echo\")\n        ws.close(1001, \"goodbye\")\n        code, reason = yield self.close_future\n        self.assertEqual(code, 1001)\n        self.assertEqual(reason, \"goodbye\")\n\n    @gen_test\n    def test_write_after_close(self):\n        ws = yield self.ws_connect(\"/close_reason\")\n        msg = yield ws.read_message()\n        self.assertIs(msg, None)\n        with self.assertRaises(WebSocketClosedError):\n            ws.write_message(\"hello\")\n\n    @gen_test\n    def test_async_prepare(self):\n        # Previously, an async prepare method triggered a bug that would\n        # result in a timeout on test shutdown (and a memory leak).\n        ws = yield self.ws_connect(\"/async_prepare\")\n        ws.write_message(\"hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_path_args(self):\n        ws = yield self.ws_connect(\"/path_args/hello\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n    @gen_test\n    def test_coroutine(self):\n        ws = yield self.ws_connect(\"/coroutine\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n    @gen_test\n    def test_check_origin_valid_no_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_valid_with_path(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"http://127.0.0.1:%d/something\" % port}\n\n        ws = yield websocket_connect(HTTPRequest(url, headers=headers))\n        ws.write_message(\"hello\")\n        response = yield ws.read_message()\n        self.assertEqual(response, \"hello\")\n\n    @gen_test\n    def test_check_origin_invalid_partial_url(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        headers = {\"Origin\": \"127.0.0.1:%d\" % port}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid(self):\n        port = self.get_http_port()\n\n        url = \"ws://127.0.0.1:%d/echo\" % port\n        # Host is 127.0.0.1, which should not be accessible from some other\n        # domain\n        headers = {\"Origin\": \"http://somewhereelse.com\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_check_origin_invalid_subdomains(self):\n        port = self.get_http_port()\n\n        url = \"ws://localhost:%d/echo\" % port\n        # Subdomains should be disallowed by default.  If we could pass a\n        # resolver to websocket_connect we could test sibling domains as well.\n        headers = {\"Origin\": \"http://subtenant.localhost\"}\n\n        with self.assertRaises(HTTPError) as cm:\n            yield websocket_connect(HTTPRequest(url, headers=headers))\n\n        self.assertEqual(cm.exception.code, 403)\n\n    @gen_test\n    def test_subprotocols(self):\n        ws = yield self.ws_connect(\n            \"/subprotocol\", subprotocols=[\"badproto\", \"goodproto\"]\n        )\n        self.assertEqual(ws.selected_subprotocol, \"goodproto\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=goodproto\")\n\n    @gen_test\n    def test_subprotocols_not_offered(self):\n        ws = yield self.ws_connect(\"/subprotocol\")\n        self.assertIs(ws.selected_subprotocol, None)\n        res = yield ws.read_message()\n        self.assertEqual(res, \"subprotocol=None\")\n\n    @gen_test\n    def test_open_coroutine(self):\n        self.message_sent = Event()\n        ws = yield self.ws_connect(\"/open_coroutine\")\n        yield ws.write_message(\"hello\")\n        self.message_sent.set()\n        res = yield ws.read_message()\n        self.assertEqual(res, \"ok\")\n\n    @gen_test\n    def test_error_in_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_error_in_async_open(self):\n        with ExpectLog(app_log, \"Uncaught exception\"):\n            ws = yield self.ws_connect(\"/error_in_async_open\")\n            res = yield ws.read_message()\n        self.assertIsNone(res)\n\n    @gen_test\n    def test_nodelay(self):\n        ws = yield self.ws_connect(\"/nodelay\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello\")\n\n\nclass NativeCoroutineOnMessageHandler(TestWebSocketHandler):\n    def initialize(self, **kwargs):\n        super().initialize(**kwargs)\n        self.sleeping = 0\n\n    async def on_message(self, message):\n        if self.sleeping > 0:\n            self.write_message(\"another coroutine is already sleeping\")\n        self.sleeping += 1\n        await gen.sleep(0.01)\n        self.sleeping -= 1\n        self.write_message(message)\n\n\nclass WebSocketNativeCoroutineTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/native\", NativeCoroutineOnMessageHandler)])\n\n    @gen_test\n    def test_native_coroutine(self):\n        ws = yield self.ws_connect(\"/native\")\n        # Send both messages immediately, coroutine must process one at a time.\n        yield ws.write_message(\"hello1\")\n        yield ws.write_message(\"hello2\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello1\")\n        res = yield ws.read_message()\n        self.assertEqual(res, \"hello2\")\n\n\nclass CompressionTestMixin(object):\n    MESSAGE = \"Hello world. Testing 123 123\"\n\n    def get_app(self):\n        class LimitedHandler(TestWebSocketHandler):\n            @property\n            def max_message_size(self):\n                return 1024\n\n            def on_message(self, message):\n                self.write_message(str(len(message)))\n\n        return Application(\n            [\n                (\n                    \"/echo\",\n                    EchoHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n                (\n                    \"/limited\",\n                    LimitedHandler,\n                    dict(compression_options=self.get_server_compression_options()),\n                ),\n            ]\n        )\n\n    def get_server_compression_options(self):\n        return None\n\n    def get_client_compression_options(self):\n        return None\n\n    def verify_wire_bytes(self, bytes_in: int, bytes_out: int) -> None:\n        raise NotImplementedError()\n\n    @gen_test\n    def test_message_sizes(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/echo\", compression_options=self.get_client_compression_options()\n        )\n        # Send the same message three times so we can measure the\n        # effect of the context_takeover options.\n        for i in range(3):\n            ws.write_message(self.MESSAGE)\n            response = yield ws.read_message()\n            self.assertEqual(response, self.MESSAGE)\n        self.assertEqual(ws.protocol._message_bytes_out, len(self.MESSAGE) * 3)\n        self.assertEqual(ws.protocol._message_bytes_in, len(self.MESSAGE) * 3)\n        self.verify_wire_bytes(ws.protocol._wire_bytes_in, ws.protocol._wire_bytes_out)\n\n    @gen_test\n    def test_size_limit(self: typing.Any):\n        ws = yield self.ws_connect(\n            \"/limited\", compression_options=self.get_client_compression_options()\n        )\n        # Small messages pass through.\n        ws.write_message(\"a\" * 128)\n        response = yield ws.read_message()\n        self.assertEqual(response, \"128\")\n        # This message is too big after decompression, but it compresses\n        # down to a size that will pass the initial checks.\n        ws.write_message(\"a\" * 2048)\n        response = yield ws.read_message()\n        self.assertIsNone(response)\n\n\nclass UncompressedTestMixin(CompressionTestMixin):\n    \"\"\"Specialization of CompressionTestMixin when we expect no compression.\"\"\"\n\n    def verify_wire_bytes(self: typing.Any, bytes_in, bytes_out):\n        # Bytes out includes the 4-byte mask key per message.\n        self.assertEqual(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertEqual(bytes_in, 3 * (len(self.MESSAGE) + 2))\n\n\nclass NoCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    pass\n\n\n# If only one side tries to compress, the extension is not negotiated.\nclass ServerOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n\nclass ClientOnlyCompressionTest(UncompressedTestMixin, WebSocketBaseTestCase):\n    def get_client_compression_options(self):\n        return {}\n\n\nclass DefaultCompressionTest(CompressionTestMixin, WebSocketBaseTestCase):\n    def get_server_compression_options(self):\n        return {}\n\n    def get_client_compression_options(self):\n        return {}\n\n    def verify_wire_bytes(self, bytes_in, bytes_out):\n        self.assertLess(bytes_out, 3 * (len(self.MESSAGE) + 6))\n        self.assertLess(bytes_in, 3 * (len(self.MESSAGE) + 2))\n        # Bytes out includes the 4 bytes mask key per message.\n        self.assertEqual(bytes_out, bytes_in + 12)\n\n\nclass MaskFunctionMixin(object):\n    # Subclasses should define self.mask(mask, data)\n    def mask(self, mask: bytes, data: bytes) -> bytes:\n        raise NotImplementedError()\n\n    def test_mask(self: typing.Any):\n        self.assertEqual(self.mask(b\"abcd\", b\"\"), b\"\")\n        self.assertEqual(self.mask(b\"abcd\", b\"b\"), b\"\\x03\")\n        self.assertEqual(self.mask(b\"abcd\", b\"54321\"), b\"TVPVP\")\n        self.assertEqual(self.mask(b\"ZXCV\", b\"98765432\"), b\"c`t`olpd\")\n        # Include test cases with \\x00 bytes (to ensure that the C\n        # extension isn't depending on null-terminated strings) and\n        # bytes with the high bit set (to smoke out signedness issues).\n        self.assertEqual(\n            self.mask(b\"\\x00\\x01\\x02\\x03\", b\"\\xff\\xfb\\xfd\\xfc\\xfe\\xfa\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfe\\xfb\",\n        )\n        self.assertEqual(\n            self.mask(b\"\\xff\\xfb\\xfd\\xfc\", b\"\\x00\\x01\\x02\\x03\\x04\\x05\"),\n            b\"\\xff\\xfa\\xff\\xff\\xfb\\xfe\",\n        )\n\n\nclass PythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return _websocket_mask_python(mask, data)\n\n\n@unittest.skipIf(speedups is None, \"tornado.speedups module not present\")\nclass CythonMaskFunctionTest(MaskFunctionMixin, unittest.TestCase):\n    def mask(self, mask, data):\n        return speedups.websocket_mask(mask, data)\n\n\nclass ServerPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_pong(self, data):\n                self.write_message(\"got pong\")\n\n        return Application([(\"/\", PingHandler)], websocket_ping_interval=0.01)\n\n    @gen_test\n    def test_server_ping(self):\n        ws = yield self.ws_connect(\"/\")\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got pong\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ClientPeriodicPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(\"got ping\")\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_client_ping(self):\n        ws = yield self.ws_connect(\"/\", ping_interval=0.01)\n        for i in range(3):\n            response = yield ws.read_message()\n            self.assertEqual(response, \"got ping\")\n        # TODO: test that the connection gets closed if ping responses stop.\n\n\nclass ManualPingTest(WebSocketBaseTestCase):\n    def get_app(self):\n        class PingHandler(TestWebSocketHandler):\n            def on_ping(self, data):\n                self.write_message(data, binary=isinstance(data, bytes))\n\n        return Application([(\"/\", PingHandler)])\n\n    @gen_test\n    def test_manual_ping(self):\n        ws = yield self.ws_connect(\"/\")\n\n        self.assertRaises(ValueError, ws.ping, \"a\" * 126)\n\n        ws.ping(\"hello\")\n        resp = yield ws.read_message()\n        # on_ping always sees bytes.\n        self.assertEqual(resp, b\"hello\")\n\n        ws.ping(b\"binary hello\")\n        resp = yield ws.read_message()\n        self.assertEqual(resp, b\"binary hello\")\n\n\nclass MaxMessageSizeTest(WebSocketBaseTestCase):\n    def get_app(self):\n        return Application([(\"/\", EchoHandler)], websocket_max_message_size=1024)\n\n    @gen_test\n    def test_large_message(self):\n        ws = yield self.ws_connect(\"/\")\n\n        # Write a message that is allowed.\n        msg = \"a\" * 1024\n        ws.write_message(msg)\n        resp = yield ws.read_message()\n        self.assertEqual(resp, msg)\n\n        # Write a message that is too large.\n        ws.write_message(msg + \"b\")\n        resp = yield ws.read_message()\n        # A message of None means the other side closed the connection.\n        self.assertIs(resp, None)\n        self.assertEqual(ws.close_code, 1009)\n        self.assertEqual(ws.close_reason, \"message too big\")\n        # TODO: Needs tests of messages split over multiple\n        # continuation frames.\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 849ms\nPrepared 1 package in 1.00s\nInstalled 1 package in 0.96ms\n + tornado==6.1.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5)\nResolved 29 packages in 20ms\nInstalled 29 packages in 114ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5\n................................................\ncollected 48 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ClientOnlyCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::ClientOnlyCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ClientPeriodicPingTest::test_client_ping\nPASSED r2e_tests.test_1::CythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::DefaultCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::DefaultCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ManualPingTest::test_manual_ping\nPASSED r2e_tests.test_1::MaxMessageSizeTest::test_large_message\nPASSED r2e_tests.test_1::NoCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::NoCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::PythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::ServerOnlyCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::ServerOnlyCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ServerPeriodicPingTest::test_server_ping\nPASSED r2e_tests.test_1::WebSocketNativeCoroutineTest::test_native_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_async_prepare\nPASSED r2e_tests.test_1::WebSocketTest::test_bad_websocket_version\nPASSED r2e_tests.test_1::WebSocketTest::test_binary_message\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid_partial_url\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid_subdomains\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_valid_no_path\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_valid_with_path\nPASSED r2e_tests.test_1::WebSocketTest::test_client_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_async_open\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_on_message\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_open\nPASSED r2e_tests.test_1::WebSocketTest::test_http_request\nPASSED r2e_tests.test_1::WebSocketTest::test_missing_websocket_key\nPASSED r2e_tests.test_1::WebSocketTest::test_nodelay\nPASSED r2e_tests.test_1::WebSocketTest::test_open_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_path_args\nPASSED r2e_tests.test_1::WebSocketTest::test_render_message\nPASSED r2e_tests.test_1::WebSocketTest::test_server_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_subprotocols\nPASSED r2e_tests.test_1::WebSocketTest::test_subprotocols_not_offered\nPASSED r2e_tests.test_1::WebSocketTest::test_unicode_message\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_callbacks\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_close_buffered_data\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_gen\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_header_echo\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_headers\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_redirect\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_success\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_network_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_write_after_close\n=================== 48 passed in 0.36s ===================\n",
    "new_commit_res_stderr": "WARNING:tornado.access:426 GET /echo (127.0.0.1) 0.29ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.24ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.20ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.21ms\nWARNING:tornado.access:400 GET /echo (127.0.0.1) 0.35ms\nWARNING:tornado.access:400 GET /echo (127.0.0.1) 0.19ms\nWARNING:tornado.access:404 GET /notfound (127.0.0.1) 0.22ms\n",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5\n................................................\ncollected 48 items\n\n=================================== ERRORS =====================================\n__________ WebSocketTest.test_websocket_http_redirect __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/testing.py\", line 98, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/testing.py\", line 612, in post_coroutine\n    self._test_generator.throw(type(e), e)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/r2e_tests/test_1.py\", line 377, in test_websocket_http_redirect\n    yield self.ws_connect(\"/redirect\")\ntornado.util.TimeoutError: Operation timed out after 5 seconds\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::ClientOnlyCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::ClientOnlyCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ClientPeriodicPingTest::test_client_ping\nPASSED r2e_tests.test_1::CythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::DefaultCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::DefaultCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ManualPingTest::test_manual_ping\nPASSED r2e_tests.test_1::MaxMessageSizeTest::test_large_message\nPASSED r2e_tests.test_1::NoCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::NoCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::PythonMaskFunctionTest::test_mask\nPASSED r2e_tests.test_1::ServerOnlyCompressionTest::test_message_sizes\nPASSED r2e_tests.test_1::ServerOnlyCompressionTest::test_size_limit\nPASSED r2e_tests.test_1::ServerPeriodicPingTest::test_server_ping\nPASSED r2e_tests.test_1::WebSocketNativeCoroutineTest::test_native_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_async_prepare\nPASSED r2e_tests.test_1::WebSocketTest::test_bad_websocket_version\nPASSED r2e_tests.test_1::WebSocketTest::test_binary_message\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid_partial_url\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_invalid_subdomains\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_valid_no_path\nPASSED r2e_tests.test_1::WebSocketTest::test_check_origin_valid_with_path\nPASSED r2e_tests.test_1::WebSocketTest::test_client_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_async_open\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_on_message\nPASSED r2e_tests.test_1::WebSocketTest::test_error_in_open\nPASSED r2e_tests.test_1::WebSocketTest::test_http_request\nPASSED r2e_tests.test_1::WebSocketTest::test_missing_websocket_key\nPASSED r2e_tests.test_1::WebSocketTest::test_nodelay\nPASSED r2e_tests.test_1::WebSocketTest::test_open_coroutine\nPASSED r2e_tests.test_1::WebSocketTest::test_path_args\nPASSED r2e_tests.test_1::WebSocketTest::test_render_message\nPASSED r2e_tests.test_1::WebSocketTest::test_server_close_reason\nPASSED r2e_tests.test_1::WebSocketTest::test_subprotocols\nPASSED r2e_tests.test_1::WebSocketTest::test_subprotocols_not_offered\nPASSED r2e_tests.test_1::WebSocketTest::test_unicode_message\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_callbacks\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_close_buffered_data\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_gen\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_header_echo\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_headers\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_fail\nERROR r2e_tests.test_1::WebSocketTest::test_websocket_http_redirect\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_http_success\nPASSED r2e_tests.test_1::WebSocketTest::test_websocket_network_fail\nPASSED r2e_tests.test_1::WebSocketTest::test_write_after_close\n=================== 1 error, 47 passed in 5.36s ===================\n",
    "old_commit_res_stderr": "WARNING:tornado.access:426 GET /echo (127.0.0.1) 0.18ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.20ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.19ms\nWARNING:tornado.access:403 GET /echo (127.0.0.1) 0.19ms\nWARNING:tornado.access:400 GET /echo (127.0.0.1) 0.19ms\nWARNING:tornado.access:400 GET /echo (127.0.0.1) 0.19ms\nWARNING:tornado.access:404 GET /notfound (127.0.0.1) 0.21ms\nERROR:tornado.application:Uncaught exception\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 273, in _read_message\n    delegate.finish()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 758, in finish\n    return self._delegate.finish()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py\", line 659, in finish\n    fut = self.client.fetch(new_request, raise_error=False)\nAttributeError: 'NoneType' object has no attribute 'fetch'\nERROR:tornado.application:Exception in callback functools.partial(<function _HTTPConnection.__init__.<locals>.<lambda> at 0x7cf5d633d160>, <Task finished name='Task-315' coro=<_HTTPConnection.run() done, defined at /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py:289> exception=_QuietException()>)\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 273, in _read_message\n    delegate.finish()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 758, in finish\n    return self._delegate.finish()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py\", line 659, in finish\n    fut = self.client.fetch(new_request, raise_error=False)\nAttributeError: 'NoneType' object has no attribute 'fetch'\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/ioloop.py\", line 741, in _run_callback\n    ret = callback()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py\", line 286, in <lambda>\n    gen.convert_yielded(self.run()), lambda f: f.result()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py\", line 440, in run\n    await self._write_body(True)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/simple_httpclient.py\", line 520, in _write_body\n    await self.connection.read_response(self)\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 273, in _read_message\n    delegate.finish()\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_5a069a8820e456bf886717898e9c21ead20289a5/tornado/http1connection.py\", line 68, in __exit__\n    raise _QuietException\ntornado.http1connection._QuietException\n"
}
tornado/test/websocket_test.py tornado/websocket.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** WebSocket Connections Follow Redirects Unexpectedly, Causing Timeout Errors

**Description:**
When attempting to establish a WebSocket connection to a URL that issues an HTTP redirect, the connection erroneously follows the redirect. This behavior is unintended for WebSocket communications and results in a timeout error because the redirected URL does not upgrade the connection to a WebSocket.

**Example Code:**
```python
from tornado.websocket import websocket_connect
from tornado.httpclient import HTTPError

# Attempting to connect to a WebSocket endpoint that redirects
try:
    ws = websocket_connect("/redirect")
except HTTPError as e:
    print(f"Connection failed with HTTP error code: {e.code}")
```

**Expected Behavior:**
The WebSocket connection should not follow HTTP redirects. Instead, it should immediately raise an error indicating that redirects are not supported for WebSocket connections.

**Actual Behavior:**
The WebSocket client follows the HTTP redirect, leading to a timeout after waiting for the connection to be established at the redirected URL.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/websocket.py
"""Implementation of the WebSocket protocol.

`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server.

WebSockets are supported in the current versions of all major browsers,
although older versions that do not support WebSockets are still in use
(refer to http://caniuse.com/websockets for details).

This module implements the final version of the WebSocket protocol as
defined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_.  Certain
browser versions (notably Safari 5.x) implemented an earlier draft of
the protocol (known as "draft 76") and are not compatible with this module.

.. versionchanged:: 4.0
   Removed support for the draft 76 protocol version.
"""

import abc
import asyncio
import base64
import hashlib
import os
import sys
import struct
import tornado.escape
import tornado.web
from urllib.parse import urlparse
import zlib

from tornado.concurrent import Future, future_set_result_unless_cancelled
from tornado.escape import utf8, native_str, to_unicode
from tornado import gen, httpclient, httputil
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.iostream import StreamClosedError, IOStream
from tornado.log import gen_log, app_log
from tornado import simple_httpclient
from tornado.queues import Queue
from tornado.tcpclient import TCPClient
from tornado.util import _websocket_mask

from typing import (
    TYPE_CHECKING,
    cast,
    Any,
    Optional,
    Dict,
    Union,
    List,
    Awaitable,
    Callable,
    Tuple,
    Type,
)
from types import TracebackType

if TYPE_CHECKING:
    from typing_extensions import Protocol

    # The zlib compressor types aren't actually exposed anywhere
    # publicly, so declare protocols for the portions we use.
    class _Compressor(Protocol):
        def compress(self, data: bytes) -> bytes:
            pass

        def flush(self, mode: int) -> bytes:
            pass

    class _Decompressor(Protocol):
        unconsumed_tail = b""  # type: bytes

        def decompress(self, data: bytes, max_length: int) -> bytes:
            pass

    class _WebSocketDelegate(Protocol):
        # The common base interface implemented by WebSocketHandler on
        # the server side and WebSocketClientConnection on the client
        # side.
        def on_ws_connection_close(
            self, close_code: Optional[int] = None, close_reason: Optional[str] = None
        ) -> None:
            pass

        def on_message(self, message: Union[str, bytes]) -> Optional["Awaitable[None]"]:
            pass

        def on_ping(self, data: bytes) -> None:
            pass

        def on_pong(self, data: bytes) -> None:
            pass

        def log_exception(
            self,
            typ: Optional[Type[BaseException]],
            value: Optional[BaseException],
            tb: Optional[TracebackType],
        ) -> None:
            pass


_default_max_message_size = 10 * 1024 * 1024


class WebSocketError(Exception):
    pass


class WebSocketClosedError(WebSocketError):
    """Raised by operations on a closed connection.

    .. versionadded:: 3.2
    """

    pass


class _DecompressTooLargeError(Exception):
    pass


class _WebSocketParams(object):
    def __init__(
        self,
        ping_interval: Optional[float] = None,
        ping_timeout: Optional[float] = None,
        max_message_size: int = _default_max_message_size,
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        self.ping_interval = ping_interval
        self.ping_timeout = ping_timeout
        self.max_message_size = max_message_size
        self.compression_options = compression_options


class WebSocketHandler(tornado.web.RequestHandler):
    """Subclass this class to create a basic WebSocket handler.

    Override `on_message` to handle incoming messages, and use
    `write_message` to send messages to the client. You can also
    override `open` and `on_close` to handle opened and closed
    connections.

    Custom upgrade response headers can be sent by overriding
    `~tornado.web.RequestHandler.set_default_headers` or
    `~tornado.web.RequestHandler.prepare`.

    See http://dev.w3.org/html5/websockets/ for details on the
    JavaScript interface.  The protocol is specified at
    http://tools.ietf.org/html/rfc6455.

    Here is an example WebSocket handler that echos back all received messages
    back to the client:

    .. testcode::

      class EchoWebSocket(tornado.websocket.WebSocketHandler):
          def open(self):
              print("WebSocket opened")

          def on_message(self, message):
              self.write_message(u"You said: " + message)

          def on_close(self):
              print("WebSocket closed")

    .. testoutput::
       :hide:

    WebSockets are not standard HTTP connections. The "handshake" is
    HTTP, but after the handshake, the protocol is
    message-based. Consequently, most of the Tornado HTTP facilities
    are not available in handlers of this type. The only communication
    methods available to you are `write_message()`, `ping()`, and
    `close()`. Likewise, your request handler class should implement
    `open()` method rather than ``get()`` or ``post()``.

    If you map the handler above to ``/websocket`` in your application, you can
    invoke it in JavaScript with::

      var ws = new WebSocket("ws://localhost:8888/websocket");
      ws.onopen = function() {
         ws.send("Hello, world");
      };
      ws.onmessage = function (evt) {
         alert(evt.data);
      };

    This script pops up an alert box that says "You said: Hello, world".

    Web browsers allow any site to open a websocket connection to any other,
    instead of using the same-origin policy that governs other network
    access from JavaScript.  This can be surprising and is a potential
    security hole, so since Tornado 4.0 `WebSocketHandler` requires
    applications that wish to receive cross-origin websockets to opt in
    by overriding the `~WebSocketHandler.check_origin` method (see that
    method's docs for details).  Failure to do so is the most likely
    cause of 403 errors when making a websocket connection.

    When using a secure websocket connection (``wss://``) with a self-signed
    certificate, the connection from a browser may fail because it wants
    to show the "accept this certificate" dialog but has nowhere to show it.
    You must first visit a regular HTML page using the same certificate
    to accept it before the websocket connection will succeed.

    If the application setting ``websocket_ping_interval`` has a non-zero
    value, a ping will be sent periodically, and the connection will be
    closed if a response is not received before the ``websocket_ping_timeout``.

    Messages larger than the ``websocket_max_message_size`` application setting
    (default 10MiB) will not be accepted.

    .. versionchanged:: 4.5
       Added ``websocket_ping_interval``, ``websocket_ping_timeout``, and
       ``websocket_max_message_size``.
    """

    def __init__(
        self,
        application: tornado.web.Application,
        request: httputil.HTTPServerRequest,
        **kwargs: Any
    ) -> None:
        super().__init__(application, request, **kwargs)
        self.ws_connection = None  # type: Optional[WebSocketProtocol]
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]
        self.stream = None  # type: Optional[IOStream]
        self._on_close_called = False

    async def get(self, *args: Any, **kwargs: Any) -> None:
        self.open_args = args
        self.open_kwargs = kwargs

        # Upgrade header should be present and should be equal to WebSocket
        if self.request.headers.get("Upgrade", "").lower() != "websocket":
            self.set_status(400)
            log_msg = 'Can "Upgrade" only to "WebSocket".'
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        # Connection header should be upgrade.
        # Some proxy servers/load balancers
        # might mess with it.
        headers = self.request.headers
        connection = map(
            lambda s: s.strip().lower(), headers.get("Connection", "").split(",")
        )
        if "upgrade" not in connection:
            self.set_status(400)
            log_msg = '"Connection" must be "Upgrade".'
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        # Handle WebSocket Origin naming convention differences
        # The difference between version 8 and 13 is that in 8 the
        # client sends a "Sec-Websocket-Origin" header and in 13 it's
        # simply "Origin".
        if "Origin" in self.request.headers:
            origin = self.request.headers.get("Origin")
        else:
            origin = self.request.headers.get("Sec-Websocket-Origin", None)

        # If there was an origin header, check to make sure it matches
        # according to check_origin. When the origin is None, we assume it
        # did not come from a browser and that it can be passed on.
        if origin is not None and not self.check_origin(origin):
            self.set_status(403)
            log_msg = "Cross origin websockets not allowed"
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        self.ws_connection = self.get_websocket_protocol()
        if self.ws_connection:
            await self.ws_connection.accept_connection(self)
        else:
            self.set_status(426, "Upgrade Required")
            self.set_header("Sec-WebSocket-Version", "7, 8, 13")

    @property
    def ping_interval(self) -> Optional[float]:
        """The interval for websocket keep-alive pings.

        Set websocket_ping_interval = 0 to disable pings.
        """
        return self.settings.get("websocket_ping_interval", None)

    @property
    def ping_timeout(self) -> Optional[float]:
        """If no ping is received in this many seconds,
        close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).
        Default is max of 3 pings or 30 seconds.
        """
        return self.settings.get("websocket_ping_timeout", None)

    @property
    def max_message_size(self) -> int:
        """Maximum allowed message size.

        If the remote peer sends a message larger than this, the connection
        will be closed.

        Default is 10MiB.
        """
        return self.settings.get(
            "websocket_max_message_size", _default_max_message_size
        )

    def write_message(
        self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False
    ) -> "Future[None]":
        """Sends the given message to the client of this Web Socket.

        The message may be either a string or a dict (which will be
        encoded as json).  If the ``binary`` argument is false, the
        message will be sent as utf8; in binary mode any byte string
        is allowed.

        If the connection is already closed, raises `WebSocketClosedError`.
        Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 3.2
           `WebSocketClosedError` was added (previously a closed connection
           would raise an `AttributeError`)

        .. versionchanged:: 4.3
           Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 5.0
           Consistently raises `WebSocketClosedError`. Previously could
           sometimes raise `.StreamClosedError`.
        """
        if self.ws_connection is None or self.ws_connection.is_closing():
            raise WebSocketClosedError()
        if isinstance(message, dict):
            message = tornado.escape.json_encode(message)
        return self.ws_connection.write_message(message, binary=binary)

    def select_subprotocol(self, subprotocols: List[str]) -> Optional[str]:
        """Override to implement subprotocol negotiation.

        ``subprotocols`` is a list of strings identifying the
        subprotocols proposed by the client.  This method may be
        overridden to return one of those strings to select it, or
        ``None`` to not select a subprotocol.

        Failure to select a subprotocol does not automatically abort
        the connection, although clients may close the connection if
        none of their proposed subprotocols was selected.

        The list may be empty, in which case this method must return
        None. This method is always called exactly once even if no
        subprotocols were proposed so that the handler can be advised
        of this fact.

        .. versionchanged:: 5.1

           Previously, this method was called with a list containing
           an empty string instead of an empty list if no subprotocols
           were proposed by the client.
        """
        return None

    @property
    def selected_subprotocol(self) -> Optional[str]:
        """The subprotocol returned by `select_subprotocol`.

        .. versionadded:: 5.1
        """
        assert self.ws_connection is not None
        return self.ws_connection.selected_subprotocol

    def get_compression_options(self) -> Optional[Dict[str, Any]]:
        """Override to return compression options for the connection.

        If this method returns None (the default), compression will
        be disabled.  If it returns a dict (even an empty one), it
        will be enabled.  The contents of the dict may be used to
        control the following compression options:

        ``compression_level`` specifies the compression level.

        ``mem_level`` specifies the amount of memory used for the internal compression state.

         These parameters are documented in details here:
         https://docs.python.org/3.6/library/zlib.html#zlib.compressobj

        .. versionadded:: 4.1

        .. versionchanged:: 4.5

           Added ``compression_level`` and ``mem_level``.
        """
        # TODO: Add wbits option.
        return None

    def open(self, *args: str, **kwargs: str) -> Optional[Awaitable[None]]:
        """Invoked when a new WebSocket is opened.

        The arguments to `open` are extracted from the `tornado.web.URLSpec`
        regular expression, just like the arguments to
        `tornado.web.RequestHandler.get`.

        `open` may be a coroutine. `on_message` will not be called until
        `open` has returned.

        .. versionchanged:: 5.1

           ``open`` may be a coroutine.
        """
        pass

    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:
        """Handle incoming messages on the WebSocket

        This method must be overridden.

        .. versionchanged:: 4.5

           ``on_message`` can be a coroutine.
        """
        raise NotImplementedError

    def ping(self, data: Union[str, bytes] = b"") -> None:
        """Send ping frame to the remote end.

        The data argument allows a small amount of data (up to 125
        bytes) to be sent as a part of the ping message. Note that not
        all websocket implementations expose this data to
        applications.

        Consider using the ``websocket_ping_interval`` application
        setting instead of sending pings manually.

        .. versionchanged:: 5.1

           The data argument is now optional.

        """
        data = utf8(data)
        if self.ws_connection is None or self.ws_connection.is_closing():
            raise WebSocketClosedError()
        self.ws_connection.write_ping(data)

    def on_pong(self, data: bytes) -> None:
        """Invoked when the response to a ping frame is received."""
        pass

    def on_ping(self, data: bytes) -> None:
        """Invoked when the a ping frame is received."""
        pass

    def on_close(self) -> None:
        """Invoked when the WebSocket is closed.

        If the connection was closed cleanly and a status code or reason
        phrase was supplied, these values will be available as the attributes
        ``self.close_code`` and ``self.close_reason``.

        .. versionchanged:: 4.0

           Added ``close_code`` and ``close_reason`` attributes.
        """
        pass

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes this Web Socket.

        Once the close handshake is successful the socket will be closed.

        ``code`` may be a numeric status code, taken from the values
        defined in `RFC 6455 section 7.4.1
        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.
        ``reason`` may be a textual message about why the connection is
        closing.  These values are made available to the client, but are
        not otherwise interpreted by the websocket protocol.

        .. versionchanged:: 4.0

           Added the ``code`` and ``reason`` arguments.
        """
        if self.ws_connection:
            self.ws_connection.close(code, reason)
            self.ws_connection = None

    def check_origin(self, origin: str) -> bool:
        """Override to enable support for allowing alternate origins.

        The ``origin`` argument is the value of the ``Origin`` HTTP
        header, the url responsible for initiating this request.  This
        method is not called for clients that do not send this header;
        such requests are always allowed (because all browsers that
        implement WebSockets support this header, and non-browser
        clients do not have the same cross-site security concerns).

        Should return ``True`` to accept the request or ``False`` to
        reject it. By default, rejects all requests with an origin on
        a host other than this one.

        This is a security protection against cross site scripting attacks on
        browsers, since WebSockets are allowed to bypass the usual same-origin
        policies and don't use CORS headers.

        .. warning::

           This is an important security measure; don't disable it
           without understanding the security implications. In
           particular, if your authentication is cookie-based, you
           must either restrict the origins allowed by
           ``check_origin()`` or implement your own XSRF-like
           protection for websocket connections. See `these
           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_
           `articles
           <https://devcenter.heroku.com/articles/websocket-security>`_
           for more.

        To accept all cross-origin traffic (which was the default prior to
        Tornado 4.0), simply override this method to always return ``True``::

            def check_origin(self, origin):
                return True

        To allow connections from any subdomain of your site, you might
        do something like::

            def check_origin(self, origin):
                parsed_origin = urllib.parse.urlparse(origin)
                return parsed_origin.netloc.endswith(".mydomain.com")

        .. versionadded:: 4.0

        """
        parsed_origin = urlparse(origin)
        origin = parsed_origin.netloc
        origin = origin.lower()

        host = self.request.headers.get("Host")

        # Check to see that origin matches host directly, including ports
        return origin == host

    def set_nodelay(self, value: bool) -> None:
        """Set the no-delay flag for this stream.

        By default, small messages may be delayed and/or combined to minimize
        the number of packets sent.  This can sometimes cause 200-500ms delays
        due to the interaction between Nagle's algorithm and TCP delayed
        ACKs.  To reduce this delay (at the expense of possibly increasing
        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket
        connection is established.

        See `.BaseIOStream.set_nodelay` for additional details.

        .. versionadded:: 3.1
        """
        assert self.ws_connection is not None
        self.ws_connection.set_nodelay(value)

    def on_connection_close(self) -> None:
        if self.ws_connection:
            self.ws_connection.on_connection_close()
            self.ws_connection = None
        if not self._on_close_called:
            self._on_close_called = True
            self.on_close()
            self._break_cycles()

    def on_ws_connection_close(
        self, close_code: Optional[int] = None, close_reason: Optional[str] = None
    ) -> None:
        self.close_code = close_code
        self.close_reason = close_reason
        self.on_connection_close()

    def _break_cycles(self) -> None:
        # WebSocketHandlers call finish() early, but we don't want to
        # break up reference cycles (which makes it impossible to call
        # self.render_string) until after we've really closed the
        # connection (if it was established in the first place,
        # indicated by status code 101).
        if self.get_status() != 101 or self._on_close_called:
            super()._break_cycles()

    def send_error(self, *args: Any, **kwargs: Any) -> None:
        if self.stream is None:
            super().send_error(*args, **kwargs)
        else:
            # If we get an uncaught exception during the handshake,
            # we have no choice but to abruptly close the connection.
            # TODO: for uncaught exceptions after the handshake,
            # we can close the connection more gracefully.
            self.stream.close()

    def get_websocket_protocol(self) -> Optional["WebSocketProtocol"]:
        websocket_version = self.request.headers.get("Sec-WebSocket-Version")
        if websocket_version in ("7", "8", "13"):
            params = _WebSocketParams(
                ping_interval=self.ping_interval,
                ping_timeout=self.ping_timeout,
                max_message_size=self.max_message_size,
                compression_options=self.get_compression_options(),
            )
            return WebSocketProtocol13(self, False, params)
        return None

    def _detach_stream(self) -> IOStream:
        # disable non-WS methods
        for method in [
            "write",
            "redirect",
            "set_header",
            "set_cookie",
            "set_status",
            "flush",
            "finish",
        ]:
            setattr(self, method, _raise_not_supported_for_websockets)
        return self.detach()


def _raise_not_supported_for_websockets(*args: Any, **kwargs: Any) -> None:
    raise RuntimeError("Method not supported for Web Sockets")


class WebSocketProtocol(abc.ABC):
    """Base class for WebSocket protocol versions.
    """

    def __init__(self, handler: "_WebSocketDelegate") -> None:
        self.handler = handler
        self.stream = None  # type: Optional[IOStream]
        self.client_terminated = False
        self.server_terminated = False

    def _run_callback(
        self, callback: Callable, *args: Any, **kwargs: Any
    ) -> "Optional[Future[Any]]":
        """Runs the given callback with exception handling.

        If the callback is a coroutine, returns its Future. On error, aborts the
        websocket connection and returns None.
        """
        try:
            result = callback(*args, **kwargs)
        except Exception:
            self.handler.log_exception(*sys.exc_info())
            self._abort()
            return None
        else:
            if result is not None:
                result = gen.convert_yielded(result)
                assert self.stream is not None
                self.stream.io_loop.add_future(result, lambda f: f.result())
            return result

    def on_connection_close(self) -> None:
        self._abort()

    def _abort(self) -> None:
        """Instantly aborts the WebSocket connection by closing the socket"""
        self.client_terminated = True
        self.server_terminated = True
        if self.stream is not None:
            self.stream.close()  # forcibly tear down the connection
        self.close()  # let the subclass cleanup

    @abc.abstractmethod
    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def is_closing(self) -> bool:
        raise NotImplementedError()

    @abc.abstractmethod
    async def accept_connection(self, handler: WebSocketHandler) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        raise NotImplementedError()

    @property
    @abc.abstractmethod
    def selected_subprotocol(self) -> Optional[str]:
        raise NotImplementedError()

    @abc.abstractmethod
    def write_ping(self, data: bytes) -> None:
        raise NotImplementedError()

    # The entry points below are used by WebSocketClientConnection,
    # which was introduced after we only supported a single version of
    # WebSocketProtocol. The WebSocketProtocol/WebSocketProtocol13
    # boundary is currently pretty ad-hoc.
    @abc.abstractmethod
    def _process_server_headers(
        self, key: Union[str, bytes], headers: httputil.HTTPHeaders
    ) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def start_pinging(self) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    async def _receive_frame_loop(self) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def set_nodelay(self, x: bool) -> None:
        raise NotImplementedError()


class _PerMessageDeflateCompressor(object):
    def __init__(
        self,
        persistent: bool,
        max_wbits: Optional[int],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        if max_wbits is None:
            max_wbits = zlib.MAX_WBITS
        # There is no symbolic constant for the minimum wbits value.
        if not (8 <= max_wbits <= zlib.MAX_WBITS):
            raise ValueError(
                "Invalid max_wbits value %r; allowed range 8-%d",
                max_wbits,
                zlib.MAX_WBITS,
            )
        self._max_wbits = max_wbits

        if (
            compression_options is None
            or "compression_level" not in compression_options
        ):
            self._compression_level = tornado.web.GZipContentEncoding.GZIP_LEVEL
        else:
            self._compression_level = compression_options["compression_level"]

        if compression_options is None or "mem_level" not in compression_options:
            self._mem_level = 8
        else:
            self._mem_level = compression_options["mem_level"]

        if persistent:
            self._compressor = self._create_compressor()  # type: Optional[_Compressor]
        else:
            self._compressor = None

    def _create_compressor(self) -> "_Compressor":
        return zlib.compressobj(
            self._compression_level, zlib.DEFLATED, -self._max_wbits, self._mem_level
        )

    def compress(self, data: bytes) -> bytes:
        compressor = self._compressor or self._create_compressor()
        data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)
        assert data.endswith(b"\x00\x00\xff\xff")
        return data[:-4]


class _PerMessageDeflateDecompressor(object):
    def __init__(
        self,
        persistent: bool,
        max_wbits: Optional[int],
        max_message_size: int,
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        self._max_message_size = max_message_size
        if max_wbits is None:
            max_wbits = zlib.MAX_WBITS
        if not (8 <= max_wbits <= zlib.MAX_WBITS):
            raise ValueError(
                "Invalid max_wbits value %r; allowed range 8-%d",
                max_wbits,
                zlib.MAX_WBITS,
            )
        self._max_wbits = max_wbits
        if persistent:
            self._decompressor = (
                self._create_decompressor()
            )  # type: Optional[_Decompressor]
        else:
            self._decompressor = None

    def _create_decompressor(self) -> "_Decompressor":
        return zlib.decompressobj(-self._max_wbits)

    def decompress(self, data: bytes) -> bytes:
        decompressor = self._decompressor or self._create_decompressor()
        result = decompressor.decompress(
            data + b"\x00\x00\xff\xff", self._max_message_size
        )
        if decompressor.unconsumed_tail:
            raise _DecompressTooLargeError()
        return result


class WebSocketProtocol13(WebSocketProtocol):
    """Implementation of the WebSocket protocol from RFC 6455.

    This class supports versions 7 and 8 of the protocol in addition to the
    final version 13.
    """

    # Bit masks for the first byte of a frame.
    FIN = 0x80
    RSV1 = 0x40
    RSV2 = 0x20
    RSV3 = 0x10
    RSV_MASK = RSV1 | RSV2 | RSV3
    OPCODE_MASK = 0x0F

    stream = None  # type: IOStream

    def __init__(
        self,
        handler: "_WebSocketDelegate",
        mask_outgoing: bool,
        params: _WebSocketParams,
    ) -> None:
        WebSocketProtocol.__init__(self, handler)
        self.mask_outgoing = mask_outgoing
        self.params = params
        self._final_frame = False
        self._frame_opcode = None
        self._masked_frame = None
        self._frame_mask = None  # type: Optional[bytes]
        self._frame_length = None
        self._fragmented_message_buffer = None  # type: Optional[bytes]
        self._fragmented_message_opcode = None
        self._waiting = None  # type: object
        self._compression_options = params.compression_options
        self._decompressor = None  # type: Optional[_PerMessageDeflateDecompressor]
        self._compressor = None  # type: Optional[_PerMessageDeflateCompressor]
        self._frame_compressed = None  # type: Optional[bool]
        # The total uncompressed size of all messages received or sent.
        # Unicode messages are encoded to utf8.
        # Only for testing; subject to change.
        self._message_bytes_in = 0
        self._message_bytes_out = 0
        # The total size of all packets received or sent.  Includes
        # the effect of compression, frame overhead, and control frames.
        self._wire_bytes_in = 0
        self._wire_bytes_out = 0
        self.ping_callback = None  # type: Optional[PeriodicCallback]
        self.last_ping = 0.0
        self.last_pong = 0.0
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]

    # Use a property for this to satisfy the abc.
    @property
    def selected_subprotocol(self) -> Optional[str]:
        return self._selected_subprotocol

    @selected_subprotocol.setter
    def selected_subprotocol(self, value: Optional[str]) -> None:
        self._selected_subprotocol = value

    async def accept_connection(self, handler: WebSocketHandler) -> None:
        try:
            self._handle_websocket_headers(handler)
        except ValueError:
            handler.set_status(400)
            log_msg = "Missing/Invalid WebSocket headers"
            handler.finish(log_msg)
            gen_log.debug(log_msg)
            return

        try:
            await self._accept_connection(handler)
        except asyncio.CancelledError:
            self._abort()
            return
        except ValueError:
            gen_log.debug("Malformed WebSocket request received", exc_info=True)
            self._abort()
            return

    def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:
        """Verifies all invariant- and required headers

        If a header is missing or have an incorrect value ValueError will be
        raised
        """
        fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version")
        if not all(map(lambda f: handler.request.headers.get(f), fields)):
            raise ValueError("Missing/Invalid WebSocket headers")

    @staticmethod
    def compute_accept_value(key: Union[str, bytes]) -> str:
        """Computes the value for the Sec-WebSocket-Accept header,
        given the value for Sec-WebSocket-Key.
        """
        sha1 = hashlib.sha1()
        sha1.update(utf8(key))
        sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")  # Magic value
        return native_str(base64.b64encode(sha1.digest()))

    def _challenge_response(self, handler: WebSocketHandler) -> str:
        return WebSocketProtocol13.compute_accept_value(
            cast(str, handler.request.headers.get("Sec-Websocket-Key"))
        )

    async def _accept_connection(self, handler: WebSocketHandler) -> None:
        subprotocol_header = handler.request.headers.get("Sec-WebSocket-Protocol")
        if subprotocol_header:
            subprotocols = [s.strip() for s in subprotocol_header.split(",")]
        else:
            subprotocols = []
        self.selected_subprotocol = handler.select_subprotocol(subprotocols)
        if self.selected_subprotocol:
            assert self.selected_subprotocol in subprotocols
            handler.set_header("Sec-WebSocket-Protocol", self.selected_subprotocol)

        extensions = self._parse_extensions_header(handler.request.headers)
        for ext in extensions:
            if ext[0] == "permessage-deflate" and self._compression_options is not None:
                # TODO: negotiate parameters if compression_options
                # specifies limits.
                self._create_compressors("server", ext[1], self._compression_options)
                if (
                    "client_max_window_bits" in ext[1]
                    and ext[1]["client_max_window_bits"] is None
                ):
                    # Don't echo an offered client_max_window_bits
                    # parameter with no value.
                    del ext[1]["client_max_window_bits"]
                handler.set_header(
                    "Sec-WebSocket-Extensions",
                    httputil._encode_header("permessage-deflate", ext[1]),
                )
                break

        handler.clear_header("Content-Type")
        handler.set_status(101)
        handler.set_header("Upgrade", "websocket")
        handler.set_header("Connection", "Upgrade")
        handler.set_header("Sec-WebSocket-Accept", self._challenge_response(handler))
        handler.finish()

        self.stream = handler._detach_stream()

        self.start_pinging()
        try:
            open_result = handler.open(*handler.open_args, **handler.open_kwargs)
            if open_result is not None:
                await open_result
        except Exception:
            handler.log_exception(*sys.exc_info())
            self._abort()
            return

        await self._receive_frame_loop()

    def _parse_extensions_header(
        self, headers: httputil.HTTPHeaders
    ) -> List[Tuple[str, Dict[str, str]]]:
        extensions = headers.get("Sec-WebSocket-Extensions", "")
        if extensions:
            return [httputil._parse_header(e.strip()) for e in extensions.split(",")]
        return []

    def _process_server_headers(
        self, key: Union[str, bytes], headers: httputil.HTTPHeaders
    ) -> None:
        """Process the headers sent by the server to this client connection.

        'key' is the websocket handshake challenge/response key.
        """
        assert headers["Upgrade"].lower() == "websocket"
        assert headers["Connection"].lower() == "upgrade"
        accept = self.compute_accept_value(key)
        assert headers["Sec-Websocket-Accept"] == accept

        extensions = self._parse_extensions_header(headers)
        for ext in extensions:
            if ext[0] == "permessage-deflate" and self._compression_options is not None:
                self._create_compressors("client", ext[1])
            else:
                raise ValueError("unsupported extension %r", ext)

        self.selected_subprotocol = headers.get("Sec-WebSocket-Protocol", None)

    def _get_compressor_options(
        self,
        side: str,
        agreed_parameters: Dict[str, Any],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Converts a websocket agreed_parameters set to keyword arguments
        for our compressor objects.
        """
        options = dict(
            persistent=(side + "_no_context_takeover") not in agreed_parameters
        )  # type: Dict[str, Any]
        wbits_header = agreed_parameters.get(side + "_max_window_bits", None)
        if wbits_header is None:
            options["max_wbits"] = zlib.MAX_WBITS
        else:
            options["max_wbits"] = int(wbits_header)
        options["compression_options"] = compression_options
        return options

    def _create_compressors(
        self,
        side: str,
        agreed_parameters: Dict[str, Any],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        # TODO: handle invalid parameters gracefully
        allowed_keys = set(
            [
                "server_no_context_takeover",
                "client_no_context_takeover",
                "server_max_window_bits",
                "client_max_window_bits",
            ]
        )
        for key in agreed_parameters:
            if key not in allowed_keys:
                raise ValueError("unsupported compression parameter %r" % key)
        other_side = "client" if (side == "server") else "server"
        self._compressor = _PerMessageDeflateCompressor(
            **self._get_compressor_options(side, agreed_parameters, compression_options)
        )
        self._decompressor = _PerMessageDeflateDecompressor(
            max_message_size=self.params.max_message_size,
            **self._get_compressor_options(
                other_side, agreed_parameters, compression_options
            )
        )

    def _write_frame(
        self, fin: bool, opcode: int, data: bytes, flags: int = 0
    ) -> "Future[None]":
        data_len = len(data)
        if opcode & 0x8:
            # All control frames MUST have a payload length of 125
            # bytes or less and MUST NOT be fragmented.
            if not fin:
                raise ValueError("control frames may not be fragmented")
            if data_len > 125:
                raise ValueError("control frame payloads may not exceed 125 bytes")
        if fin:
            finbit = self.FIN
        else:
            finbit = 0
        frame = struct.pack("B", finbit | opcode | flags)
        if self.mask_outgoing:
            mask_bit = 0x80
        else:
            mask_bit = 0
        if data_len < 126:
            frame += struct.pack("B", data_len | mask_bit)
        elif data_len <= 0xFFFF:
            frame += struct.pack("!BH", 126 | mask_bit, data_len)
        else:
            frame += struct.pack("!BQ", 127 | mask_bit, data_len)
        if self.mask_outgoing:
            mask = os.urandom(4)
            data = mask + _websocket_mask(mask, data)
        frame += data
        self._wire_bytes_out += len(frame)
        return self.stream.write(frame)

    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        """Sends the given message to the client of this Web Socket."""
        if binary:
            opcode = 0x2
        else:
            opcode = 0x1
        message = tornado.escape.utf8(message)
        assert isinstance(message, bytes)
        self._message_bytes_out += len(message)
        flags = 0
        if self._compressor:
            message = self._compressor.compress(message)
            flags |= self.RSV1
        # For historical reasons, write methods in Tornado operate in a semi-synchronous
        # mode in which awaiting the Future they return is optional (But errors can
        # still be raised). This requires us to go through an awkward dance here
        # to transform the errors that may be returned while presenting the same
        # semi-synchronous interface.
        try:
            fut = self._write_frame(True, opcode, message, flags=flags)
        except StreamClosedError:
            raise WebSocketClosedError()

        async def wrapper() -> None:
            try:
                await fut
            except StreamClosedError:
                raise WebSocketClosedError()

        return asyncio.ensure_future(wrapper())

    def write_ping(self, data: bytes) -> None:
        """Send ping frame."""
        assert isinstance(data, bytes)
        self._write_frame(True, 0x9, data)

    async def _receive_frame_loop(self) -> None:
        try:
            while not self.client_terminated:
                await self._receive_frame()
        except StreamClosedError:
            self._abort()
        self.handler.on_ws_connection_close(self.close_code, self.close_reason)

    async def _read_bytes(self, n: int) -> bytes:
        data = await self.stream.read_bytes(n)
        self._wire_bytes_in += n
        return data

    async def _receive_frame(self) -> None:
        # Read the frame header.
        data = await self._read_bytes(2)
        header, mask_payloadlen = struct.unpack("BB", data)
        is_final_frame = header & self.FIN
        reserved_bits = header & self.RSV_MASK
        opcode = header & self.OPCODE_MASK
        opcode_is_control = opcode & 0x8
        if self._decompressor is not None and opcode != 0:
            # Compression flag is present in the first frame's header,
            # but we can't decompress until we have all the frames of
            # the message.
            self._frame_compressed = bool(reserved_bits & self.RSV1)
            reserved_bits &= ~self.RSV1
        if reserved_bits:
            # client is using as-yet-undefined extensions; abort
            self._abort()
            return
        is_masked = bool(mask_payloadlen & 0x80)
        payloadlen = mask_payloadlen & 0x7F

        # Parse and validate the length.
        if opcode_is_control and payloadlen >= 126:
            # control frames must have payload < 126
            self._abort()
            return
        if payloadlen < 126:
            self._frame_length = payloadlen
        elif payloadlen == 126:
            data = await self._read_bytes(2)
            payloadlen = struct.unpack("!H", data)[0]
        elif payloadlen == 127:
            data = await self._read_bytes(8)
            payloadlen = struct.unpack("!Q", data)[0]
        new_len = payloadlen
        if self._fragmented_message_buffer is not None:
            new_len += len(self._fragmented_message_buffer)
        if new_len > self.params.max_message_size:
            self.close(1009, "message too big")
            self._abort()
            return

        # Read the payload, unmasking if necessary.
        if is_masked:
            self._frame_mask = await self._read_bytes(4)
        data = await self._read_bytes(payloadlen)
        if is_masked:
            assert self._frame_mask is not None
            data = _websocket_mask(self._frame_mask, data)

        # Decide what to do with this frame.
        if opcode_is_control:
            # control frames may be interleaved with a series of fragmented
            # data frames, so control frames must not interact with
            # self._fragmented_*
            if not is_final_frame:
                # control frames must not be fragmented
                self._abort()
                return
        elif opcode == 0:  # continuation frame
            if self._fragmented_message_buffer is None:
                # nothing to continue
                self._abort()
                return
            self._fragmented_message_buffer += data
            if is_final_frame:
                opcode = self._fragmented_message_opcode
                data = self._fragmented_message_buffer
                self._fragmented_message_buffer = None
        else:  # start of new data message
            if self._fragmented_message_buffer is not None:
                # can't start new message until the old one is finished
                self._abort()
                return
            if not is_final_frame:
                self._fragmented_message_opcode = opcode
                self._fragmented_message_buffer = data

        if is_final_frame:
            handled_future = self._handle_message(opcode, data)
            if handled_future is not None:
                await handled_future

    def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]":
        """Execute on_message, returning its Future if it is a coroutine."""
        if self.client_terminated:
            return None

        if self._frame_compressed:
            assert self._decompressor is not None
            try:
                data = self._decompressor.decompress(data)
            except _DecompressTooLargeError:
                self.close(1009, "message too big after decompression")
                self._abort()
                return None

        if opcode == 0x1:
            # UTF-8 data
            self._message_bytes_in += len(data)
            try:
                decoded = data.decode("utf-8")
            except UnicodeDecodeError:
                self._abort()
                return None
            return self._run_callback(self.handler.on_message, decoded)
        elif opcode == 0x2:
            # Binary data
            self._message_bytes_in += len(data)
            return self._run_callback(self.handler.on_message, data)
        elif opcode == 0x8:
            # Close
            self.client_terminated = True
            if len(data) >= 2:
                self.close_code = struct.unpack(">H", data[:2])[0]
            if len(data) > 2:
                self.close_reason = to_unicode(data[2:])
            # Echo the received close code, if any (RFC 6455 section 5.5.1).
            self.close(self.close_code)
        elif opcode == 0x9:
            # Ping
            try:
                self._write_frame(True, 0xA, data)
            except StreamClosedError:
                self._abort()
            self._run_callback(self.handler.on_ping, data)
        elif opcode == 0xA:
            # Pong
            self.last_pong = IOLoop.current().time()
            return self._run_callback(self.handler.on_pong, data)
        else:
            self._abort()
        return None

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes the WebSocket connection."""
        if not self.server_terminated:
            if not self.stream.closed():
                if code is None and reason is not None:
                    code = 1000  # "normal closure" status code
                if code is None:
                    close_data = b""
                else:
                    close_data = struct.pack(">H", code)
                if reason is not None:
                    close_data += utf8(reason)
                try:
                    self._write_frame(True, 0x8, close_data)
                except StreamClosedError:
                    self._abort()
            self.server_terminated = True
        if self.client_terminated:
            if self._waiting is not None:
                self.stream.io_loop.remove_timeout(self._waiting)
                self._waiting = None
            self.stream.close()
        elif self._waiting is None:
            # Give the client a few seconds to complete a clean shutdown,
            # otherwise just close the connection.
            self._waiting = self.stream.io_loop.add_timeout(
                self.stream.io_loop.time() + 5, self._abort
            )
        if self.ping_callback:
            self.ping_callback.stop()
            self.ping_callback = None

    def is_closing(self) -> bool:
        """Return ``True`` if this connection is closing.

        The connection is considered closing if either side has
        initiated its closing handshake or if the stream has been
        shut down uncleanly.
        """
        return self.stream.closed() or self.client_terminated or self.server_terminated

    @property
    def ping_interval(self) -> Optional[float]:
        interval = self.params.ping_interval
        if interval is not None:
            return interval
        return 0

    @property
    def ping_timeout(self) -> Optional[float]:
        timeout = self.params.ping_timeout
        if timeout is not None:
            return timeout
        assert self.ping_interval is not None
        return max(3 * self.ping_interval, 30)

    def start_pinging(self) -> None:
        """Start sending periodic pings to keep the connection alive"""
        assert self.ping_interval is not None
        if self.ping_interval > 0:
            self.last_ping = self.last_pong = IOLoop.current().time()
            self.ping_callback = PeriodicCallback(
                self.periodic_ping, self.ping_interval * 1000
            )
            self.ping_callback.start()

    def periodic_ping(self) -> None:
        """Send a ping to keep the websocket alive

        Called periodically if the websocket_ping_interval is set and non-zero.
        """
        if self.is_closing() and self.ping_callback is not None:
            self.ping_callback.stop()
            return

        # Check for timeout on pong. Make sure that we really have
        # sent a recent ping in case the machine with both server and
        # client has been suspended since the last ping.
        now = IOLoop.current().time()
        since_last_pong = now - self.last_pong
        since_last_ping = now - self.last_ping
        assert self.ping_interval is not None
        assert self.ping_timeout is not None
        if (
            since_last_ping < 2 * self.ping_interval
            and since_last_pong > self.ping_timeout
        ):
            self.close()
            return

        self.write_ping(b"")
        self.last_ping = now

    def set_nodelay(self, x: bool) -> None:
        self.stream.set_nodelay(x)


class WebSocketClientConnection(simple_httpclient._HTTPConnection):
    """WebSocket client connection.

    This class should not be instantiated directly; use the
    `websocket_connect` function instead.
    """

    protocol = None  # type: WebSocketProtocol

    def __init__(
        self,
        request: httpclient.HTTPRequest,
        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
        compression_options: Optional[Dict[str, Any]] = None,
        ping_interval: Optional[float] = None,
        ping_timeout: Optional[float] = None,
        max_message_size: int = _default_max_message_size,
        subprotocols: Optional[List[str]] = [],
    ) -> None:
        self.connect_future = Future()  # type: Future[WebSocketClientConnection]
        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]
        self.params = _WebSocketParams(
            ping_interval=ping_interval,
            ping_timeout=ping_timeout,
            max_message_size=max_message_size,
            compression_options=compression_options,
        )

        scheme, sep, rest = request.url.partition(":")
        scheme = {"ws": "http", "wss": "https"}[scheme]
        request.url = scheme + sep + rest
        request.headers.update(
            {
                "Upgrade": "websocket",
                "Connection": "Upgrade",
                "Sec-WebSocket-Key": self.key,
                "Sec-WebSocket-Version": "13",
            }
        )
        if subprotocols is not None:
            request.headers["Sec-WebSocket-Protocol"] = ",".join(subprotocols)
        if compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers[
                "Sec-WebSocket-Extensions"
            ] = "permessage-deflate; client_max_window_bits"

        self.tcp_client = TCPClient()
        super().__init__(
            None,
            request,
            lambda: None,
            self._on_http_response,
            104857600,
            self.tcp_client,
            65536,
            104857600,
        )

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes the websocket connection.

        ``code`` and ``reason`` are documented under
        `WebSocketHandler.close`.

        .. versionadded:: 3.2

        .. versionchanged:: 4.0

           Added the ``code`` and ``reason`` arguments.
        """
        if self.protocol is not None:
            self.protocol.close(code, reason)
            self.protocol = None  # type: ignore

    def on_connection_close(self) -> None:
        if not self.connect_future.done():
            self.connect_future.set_exception(StreamClosedError())
        self._on_message(None)
        self.tcp_client.close()
        super().on_connection_close()

    def on_ws_connection_close(
        self, close_code: Optional[int] = None, close_reason: Optional[str] = None
    ) -> None:
        self.close_code = close_code
        self.close_reason = close_reason
        self.on_connection_close()

    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:
        if not self.connect_future.done():
            if response.error:
                self.connect_future.set_exception(response.error)
            else:
                self.connect_future.set_exception(
                    WebSocketError("Non-websocket response")
                )

    async def headers_received(
        self,
        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
        headers: httputil.HTTPHeaders,
    ) -> None:
        assert isinstance(start_line, httputil.ResponseStartLine)
        if start_line.code != 101:
            await super().headers_received(start_line, headers)
            return

        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

        self.headers = headers
        self.protocol = self.get_websocket_protocol()
        self.protocol._process_server_headers(self.key, self.headers)
        self.protocol.stream = self.connection.detach()

        IOLoop.current().add_callback(self.protocol._receive_frame_loop)
        self.protocol.start_pinging()

        # Once we've taken over the connection, clear the final callback
        # we set on the http request.  This deactivates the error handling
        # in simple_httpclient that would otherwise interfere with our
        # ability to see exceptions.
        self.final_callback = None  # type: ignore

        future_set_result_unless_cancelled(self.connect_future, self)

    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        """Sends a message to the WebSocket server.

        If the stream is closed, raises `WebSocketClosedError`.
        Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 5.0
           Exception raised on a closed stream changed from `.StreamClosedError`
           to `WebSocketClosedError`.
        """
        return self.protocol.write_message(message, binary=binary)

    def read_message(
        self,
        callback: Optional[Callable[["Future[Union[None, str, bytes]]"], None]] = None,
    ) -> Awaitable[Union[None, str, bytes]]:
        """Reads a message from the WebSocket server.

        If on_message_callback was specified at WebSocket
        initialization, this function will never return messages

        Returns a future whose result is the message, or None
        if the connection is closed.  If a callback argument
        is given it will be called with the future when it is
        ready.
        """

        awaitable = self.read_queue.get()
        if callback is not None:
            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)
        return awaitable

    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:
        return self._on_message(message)

    def _on_message(
        self, message: Union[None, str, bytes]
    ) -> Optional[Awaitable[None]]:
        if self._on_message_callback:
            self._on_message_callback(message)
            return None
        else:
            return self.read_queue.put(message)

    def ping(self, data: bytes = b"") -> None:
        """Send ping frame to the remote end.

        The data argument allows a small amount of data (up to 125
        bytes) to be sent as a part of the ping message. Note that not
        all websocket implementations expose this data to
        applications.

        Consider using the ``ping_interval`` argument to
        `websocket_connect` instead of sending pings manually.

        .. versionadded:: 5.1

        """
        data = utf8(data)
        if self.protocol is None:
            raise WebSocketClosedError()
        self.protocol.write_ping(data)

    def on_pong(self, data: bytes) -> None:
        pass

    def on_ping(self, data: bytes) -> None:
        pass

    def get_websocket_protocol(self) -> WebSocketProtocol:
        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)

    @property
    def selected_subprotocol(self) -> Optional[str]:
        """The subprotocol selected by the server.

        .. versionadded:: 5.1
        """
        return self.protocol.selected_subprotocol

    def log_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        assert typ is not None
        assert value is not None
        app_log.error("Uncaught exception %s", value, exc_info=(typ, value, tb))


def websocket_connect(
    url: Union[str, httpclient.HTTPRequest],
    callback: Optional[Callable[["Future[WebSocketClientConnection]"], None]] = None,
    connect_timeout: Optional[float] = None,
    on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
    compression_options: Optional[Dict[str, Any]] = None,
    ping_interval: Optional[float] = None,
    ping_timeout: Optional[float] = None,
    max_message_size: int = _default_max_message_size,
    subprotocols: Optional[List[str]] = None,
) -> "Awaitable[WebSocketClientConnection]":
    """Client-side websocket support.

    Takes a url and returns a Future whose result is a
    `WebSocketClientConnection`.

    ``compression_options`` is interpreted in the same way as the
    return value of `.WebSocketHandler.get_compression_options`.

    The connection supports two styles of operation. In the coroutine
    style, the application typically calls
    `~.WebSocketClientConnection.read_message` in a loop::

        conn = yield websocket_connect(url)
        while True:
            msg = yield conn.read_message()
            if msg is None: break
            # Do something with msg

    In the callback style, pass an ``on_message_callback`` to
    ``websocket_connect``. In both styles, a message of ``None``
    indicates that the connection has been closed.

    ``subprotocols`` may be a list of strings specifying proposed
    subprotocols. The selected protocol may be found on the
    ``selected_subprotocol`` attribute of the connection object
    when the connection is complete.

    .. versionchanged:: 3.2
       Also accepts ``HTTPRequest`` objects in place of urls.

    .. versionchanged:: 4.1
       Added ``compression_options`` and ``on_message_callback``.

    .. versionchanged:: 4.5
       Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size``
       arguments, which have the same meaning as in `WebSocketHandler`.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.1
       Added the ``subprotocols`` argument.
    """
    if isinstance(url, httpclient.HTTPRequest):
        assert connect_timeout is None
        request = url
        # Copy and convert the headers dict/object (see comments in
        # AsyncHTTPClient.fetch)
        request.headers = httputil.HTTPHeaders(request.headers)
    else:
        request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)
    request = cast(
        httpclient.HTTPRequest,
        httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS),
    )
    conn = WebSocketClientConnection(
        request,
        on_message_callback=on_message_callback,
        compression_options=compression_options,
        ping_interval=ping_interval,
        ping_timeout=ping_timeout,
        max_message_size=max_message_size,
        subprotocols=subprotocols,
    )
    if callback is not None:
        IOLoop.current().add_future(conn.connect_future, callback)
    return conn.connect_future

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]

**Title:** WebSocket Connections Follow Redirects Unexpectedly, Causing Timeout Errors

**Description:**
When attempting to establish a WebSocket connection to a URL that issues an HTTP redirect, the connection erroneously follows the redirect. This behavior is unintended for WebSocket communications and results in a timeout error because the redirected URL does not upgrade the connection to a WebSocket.

**Example Code:**
```python
from tornado.websocket import websocket_connect
from tornado.httpclient import HTTPError

# Attempting to connect to a WebSocket endpoint that redirects
try:
    ws = websocket_connect("/redirect")
except HTTPError as e:
    print(f"Connection failed with HTTP error code: {e.code}")
```

**Expected Behavior:**
The WebSocket connection should not follow HTTP redirects. Instead, it should immediately raise an error indicating that redirects are not supported for WebSocket connections.

**Actual Behavior:**
The WebSocket client follows the HTTP redirect, leading to a timeout after waiting for the connection to be established at the redirected URL.

[/ISSUE]
{
    "ClientOnlyCompressionTest.test_message_sizes": "PASSED",
    "ClientOnlyCompressionTest.test_size_limit": "PASSED",
    "ClientPeriodicPingTest.test_client_ping": "PASSED",
    "CythonMaskFunctionTest.test_mask": "PASSED",
    "DefaultCompressionTest.test_message_sizes": "PASSED",
    "DefaultCompressionTest.test_size_limit": "PASSED",
    "ManualPingTest.test_manual_ping": "PASSED",
    "MaxMessageSizeTest.test_large_message": "PASSED",
    "NoCompressionTest.test_message_sizes": "PASSED",
    "NoCompressionTest.test_size_limit": "PASSED",
    "PythonMaskFunctionTest.test_mask": "PASSED",
    "ServerOnlyCompressionTest.test_message_sizes": "PASSED",
    "ServerOnlyCompressionTest.test_size_limit": "PASSED",
    "ServerPeriodicPingTest.test_server_ping": "PASSED",
    "WebSocketNativeCoroutineTest.test_native_coroutine": "PASSED",
    "WebSocketTest.test_async_prepare": "PASSED",
    "WebSocketTest.test_bad_websocket_version": "PASSED",
    "WebSocketTest.test_binary_message": "PASSED",
    "WebSocketTest.test_check_origin_invalid": "PASSED",
    "WebSocketTest.test_check_origin_invalid_partial_url": "PASSED",
    "WebSocketTest.test_check_origin_invalid_subdomains": "PASSED",
    "WebSocketTest.test_check_origin_valid_no_path": "PASSED",
    "WebSocketTest.test_check_origin_valid_with_path": "PASSED",
    "WebSocketTest.test_client_close_reason": "PASSED",
    "WebSocketTest.test_coroutine": "PASSED",
    "WebSocketTest.test_error_in_async_open": "PASSED",
    "WebSocketTest.test_error_in_on_message": "PASSED",
    "WebSocketTest.test_error_in_open": "PASSED",
    "WebSocketTest.test_http_request": "PASSED",
    "WebSocketTest.test_missing_websocket_key": "PASSED",
    "WebSocketTest.test_nodelay": "PASSED",
    "WebSocketTest.test_open_coroutine": "PASSED",
    "WebSocketTest.test_path_args": "PASSED",
    "WebSocketTest.test_render_message": "PASSED",
    "WebSocketTest.test_server_close_reason": "PASSED",
    "WebSocketTest.test_subprotocols": "PASSED",
    "WebSocketTest.test_subprotocols_not_offered": "PASSED",
    "WebSocketTest.test_unicode_message": "PASSED",
    "WebSocketTest.test_websocket_callbacks": "PASSED",
    "WebSocketTest.test_websocket_close_buffered_data": "PASSED",
    "WebSocketTest.test_websocket_gen": "PASSED",
    "WebSocketTest.test_websocket_header_echo": "PASSED",
    "WebSocketTest.test_websocket_headers": "PASSED",
    "WebSocketTest.test_websocket_http_fail": "PASSED",
    "WebSocketTest.test_websocket_http_redirect": "PASSED",
    "WebSocketTest.test_websocket_http_success": "PASSED",
    "WebSocketTest.test_websocket_network_fail": "PASSED",
    "WebSocketTest.test_write_after_close": "PASSED"
}
diff --git a/tornado/websocket.py b/tornado/websocket.py
index ff0c2416..eef49e7c 100644
--- a/tornado/websocket.py
+++ b/tornado/websocket.py
@@ -1409,6 +1409,9 @@ class WebSocketClientConnection(simple_httpclient._HTTPConnection):
                 "Sec-WebSocket-Extensions"
             ] = "permessage-deflate; client_max_window_bits"
 
+        # Websocket connection is currently unable to follow redirects
+        request.follow_redirects = False
+
         self.tcp_client = TCPClient()
         super().__init__(
             None,
 

{"tornado/websocket.py": "\"\"\"Implementation of the WebSocket protocol.\n\n`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional\ncommunication between the browser and server.\n\nWebSockets are supported in the current versions of all major browsers,\nalthough older versions that do not support WebSockets are still in use\n(refer to http://caniuse.com/websockets for details).\n\nThis module implements the final version of the WebSocket protocol as\ndefined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_.  Certain\nbrowser versions (notably Safari 5.x) implemented an earlier draft of\nthe protocol (known as \"draft 76\") and are not compatible with this module.\n\n.. versionchanged:: 4.0\n   Removed support for the draft 76 protocol version.\n\"\"\"\n\nimport abc\nimport asyncio\nimport base64\nimport hashlib\nimport os\nimport sys\nimport struct\nimport tornado.escape\nimport tornado.web\nfrom urllib.parse import urlparse\nimport zlib\n\nfrom tornado.concurrent import Future, future_set_result_unless_cancelled\nfrom tornado.escape import utf8, native_str, to_unicode\nfrom tornado import gen, httpclient, httputil\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.iostream import StreamClosedError, IOStream\nfrom tornado.log import gen_log, app_log\nfrom tornado import simple_httpclient\nfrom tornado.queues import Queue\nfrom tornado.tcpclient import TCPClient\nfrom tornado.util import _websocket_mask\n\nfrom typing import (\n    TYPE_CHECKING,\n    cast,\n    Any,\n    Optional,\n    Dict,\n    Union,\n    List,\n    Awaitable,\n    Callable,\n    Tuple,\n    Type,\n)\nfrom types import TracebackType\n\nif TYPE_CHECKING:\n    from typing_extensions import Protocol\n\n    # The zlib compressor types aren't actually exposed anywhere\n    # publicly, so declare protocols for the portions we use.\n    class _Compressor(Protocol):\n        def compress(self, data: bytes) -> bytes:\n            pass\n\n        def flush(self, mode: int) -> bytes:\n            pass\n\n    class _Decompressor(Protocol):\n        unconsumed_tail = b\"\"  # type: bytes\n\n        def decompress(self, data: bytes, max_length: int) -> bytes:\n            pass\n\n    class _WebSocketDelegate(Protocol):\n        # The common base interface implemented by WebSocketHandler on\n        # the server side and WebSocketClientConnection on the client\n        # side.\n        def on_ws_connection_close(\n            self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n        ) -> None:\n            pass\n\n        def on_message(self, message: Union[str, bytes]) -> Optional[\"Awaitable[None]\"]:\n            pass\n\n        def on_ping(self, data: bytes) -> None:\n            pass\n\n        def on_pong(self, data: bytes) -> None:\n            pass\n\n        def log_exception(\n            self,\n            typ: Optional[Type[BaseException]],\n            value: Optional[BaseException],\n            tb: Optional[TracebackType],\n        ) -> None:\n            pass\n\n\n_default_max_message_size = 10 * 1024 * 1024\n\n\nclass WebSocketError(Exception):\n    pass\n\n\nclass WebSocketClosedError(WebSocketError):\n    \"\"\"Raised by operations on a closed connection.\n\n    .. versionadded:: 3.2\n    \"\"\"\n\n    pass\n\n\nclass _DecompressTooLargeError(Exception):\n    pass\n\n\nclass _WebSocketParams(object):\n    def __init__(\n        self,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self.ping_interval = ping_interval\n        self.ping_timeout = ping_timeout\n        self.max_message_size = max_message_size\n        self.compression_options = compression_options\n\n\nclass WebSocketHandler(tornado.web.RequestHandler):\n    \"\"\"Subclass this class to create a basic WebSocket handler.\n\n    Override `on_message` to handle incoming messages, and use\n    `write_message` to send messages to the client. You can also\n    override `open` and `on_close` to handle opened and closed\n    connections.\n\n    Custom upgrade response headers can be sent by overriding\n    `~tornado.web.RequestHandler.set_default_headers` or\n    `~tornado.web.RequestHandler.prepare`.\n\n    See http://dev.w3.org/html5/websockets/ for details on the\n    JavaScript interface.  The protocol is specified at\n    http://tools.ietf.org/html/rfc6455.\n\n    Here is an example WebSocket handler that echos back all received messages\n    back to the client:\n\n    .. testcode::\n\n      class EchoWebSocket(tornado.websocket.WebSocketHandler):\n          def open(self):\n              print(\"WebSocket opened\")\n\n          def on_message(self, message):\n              self.write_message(u\"You said: \" + message)\n\n          def on_close(self):\n              print(\"WebSocket closed\")\n\n    .. testoutput::\n       :hide:\n\n    WebSockets are not standard HTTP connections. The \"handshake\" is\n    HTTP, but after the handshake, the protocol is\n    message-based. Consequently, most of the Tornado HTTP facilities\n    are not available in handlers of this type. The only communication\n    methods available to you are `write_message()`, `ping()`, and\n    `close()`. Likewise, your request handler class should implement\n    `open()` method rather than ``get()`` or ``post()``.\n\n    If you map the handler above to ``/websocket`` in your application, you can\n    invoke it in JavaScript with::\n\n      var ws = new WebSocket(\"ws://localhost:8888/websocket\");\n      ws.onopen = function() {\n         ws.send(\"Hello, world\");\n      };\n      ws.onmessage = function (evt) {\n         alert(evt.data);\n      };\n\n    This script pops up an alert box that says \"You said: Hello, world\".\n\n    Web browsers allow any site to open a websocket connection to any other,\n    instead of using the same-origin policy that governs other network\n    access from JavaScript.  This can be surprising and is a potential\n    security hole, so since Tornado 4.0 `WebSocketHandler` requires\n    applications that wish to receive cross-origin websockets to opt in\n    by overriding the `~WebSocketHandler.check_origin` method (see that\n    method's docs for details).  Failure to do so is the most likely\n    cause of 403 errors when making a websocket connection.\n\n    When using a secure websocket connection (``wss://``) with a self-signed\n    certificate, the connection from a browser may fail because it wants\n    to show the \"accept this certificate\" dialog but has nowhere to show it.\n    You must first visit a regular HTML page using the same certificate\n    to accept it before the websocket connection will succeed.\n\n    If the application setting ``websocket_ping_interval`` has a non-zero\n    value, a ping will be sent periodically, and the connection will be\n    closed if a response is not received before the ``websocket_ping_timeout``.\n\n    Messages larger than the ``websocket_max_message_size`` application setting\n    (default 10MiB) will not be accepted.\n\n    .. versionchanged:: 4.5\n       Added ``websocket_ping_interval``, ``websocket_ping_timeout``, and\n       ``websocket_max_message_size``.\n    \"\"\"\n\n    def __init__(\n        self,\n        application: tornado.web.Application,\n        request: httputil.HTTPServerRequest,\n        **kwargs: Any\n    ) -> None:\n        super().__init__(application, request, **kwargs)\n        self.ws_connection = None  # type: Optional[WebSocketProtocol]\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.stream = None  # type: Optional[IOStream]\n        self._on_close_called = False\n\n    async def get(self, *args: Any, **kwargs: Any) -> None:\n        self.open_args = args\n        self.open_kwargs = kwargs\n\n        # Upgrade header should be present and should be equal to WebSocket\n        if self.request.headers.get(\"Upgrade\", \"\").lower() != \"websocket\":\n            self.set_status(400)\n            log_msg = 'Can \"Upgrade\" only to \"WebSocket\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Connection header should be upgrade.\n        # Some proxy servers/load balancers\n        # might mess with it.\n        headers = self.request.headers\n        connection = map(\n            lambda s: s.strip().lower(), headers.get(\"Connection\", \"\").split(\",\")\n        )\n        if \"upgrade\" not in connection:\n            self.set_status(400)\n            log_msg = '\"Connection\" must be \"Upgrade\".'\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        # Handle WebSocket Origin naming convention differences\n        # The difference between version 8 and 13 is that in 8 the\n        # client sends a \"Sec-Websocket-Origin\" header and in 13 it's\n        # simply \"Origin\".\n        if \"Origin\" in self.request.headers:\n            origin = self.request.headers.get(\"Origin\")\n        else:\n            origin = self.request.headers.get(\"Sec-Websocket-Origin\", None)\n\n        # If there was an origin header, check to make sure it matches\n        # according to check_origin. When the origin is None, we assume it\n        # did not come from a browser and that it can be passed on.\n        if origin is not None and not self.check_origin(origin):\n            self.set_status(403)\n            log_msg = \"Cross origin websockets not allowed\"\n            self.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        self.ws_connection = self.get_websocket_protocol()\n        if self.ws_connection:\n            await self.ws_connection.accept_connection(self)\n        else:\n            self.set_status(426, \"Upgrade Required\")\n            self.set_header(\"Sec-WebSocket-Version\", \"7, 8, 13\")\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        \"\"\"The interval for websocket keep-alive pings.\n\n        Set websocket_ping_interval = 0 to disable pings.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_interval\", None)\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        \"\"\"If no ping is received in this many seconds,\n        close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).\n        Default is max of 3 pings or 30 seconds.\n        \"\"\"\n        return self.settings.get(\"websocket_ping_timeout\", None)\n\n    @property\n    def max_message_size(self) -> int:\n        \"\"\"Maximum allowed message size.\n\n        If the remote peer sends a message larger than this, the connection\n        will be closed.\n\n        Default is 10MiB.\n        \"\"\"\n        return self.settings.get(\n            \"websocket_max_message_size\", _default_max_message_size\n        )\n\n    def write_message(\n        self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\n\n        The message may be either a string or a dict (which will be\n        encoded as json).  If the ``binary`` argument is false, the\n        message will be sent as utf8; in binary mode any byte string\n        is allowed.\n\n        If the connection is already closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 3.2\n           `WebSocketClosedError` was added (previously a closed connection\n           would raise an `AttributeError`)\n\n        .. versionchanged:: 4.3\n           Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Consistently raises `WebSocketClosedError`. Previously could\n           sometimes raise `.StreamClosedError`.\n        \"\"\"\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        if isinstance(message, dict):\n            message = tornado.escape.json_encode(message)\n        return self.ws_connection.write_message(message, binary=binary)\n\n    def select_subprotocol(self, subprotocols: List[str]) -> Optional[str]:\n        \"\"\"Override to implement subprotocol negotiation.\n\n        ``subprotocols`` is a list of strings identifying the\n        subprotocols proposed by the client.  This method may be\n        overridden to return one of those strings to select it, or\n        ``None`` to not select a subprotocol.\n\n        Failure to select a subprotocol does not automatically abort\n        the connection, although clients may close the connection if\n        none of their proposed subprotocols was selected.\n\n        The list may be empty, in which case this method must return\n        None. This method is always called exactly once even if no\n        subprotocols were proposed so that the handler can be advised\n        of this fact.\n\n        .. versionchanged:: 5.1\n\n           Previously, this method was called with a list containing\n           an empty string instead of an empty list if no subprotocols\n           were proposed by the client.\n        \"\"\"\n        return None\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol returned by `select_subprotocol`.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        assert self.ws_connection is not None\n        return self.ws_connection.selected_subprotocol\n\n    def get_compression_options(self) -> Optional[Dict[str, Any]]:\n        \"\"\"Override to return compression options for the connection.\n\n        If this method returns None (the default), compression will\n        be disabled.  If it returns a dict (even an empty one), it\n        will be enabled.  The contents of the dict may be used to\n        control the following compression options:\n\n        ``compression_level`` specifies the compression level.\n\n        ``mem_level`` specifies the amount of memory used for the internal compression state.\n\n         These parameters are documented in details here:\n         https://docs.python.org/3.6/library/zlib.html#zlib.compressobj\n\n        .. versionadded:: 4.1\n\n        .. versionchanged:: 4.5\n\n           Added ``compression_level`` and ``mem_level``.\n        \"\"\"\n        # TODO: Add wbits option.\n        return None\n\n    def open(self, *args: str, **kwargs: str) -> Optional[Awaitable[None]]:\n        \"\"\"Invoked when a new WebSocket is opened.\n\n        The arguments to `open` are extracted from the `tornado.web.URLSpec`\n        regular expression, just like the arguments to\n        `tornado.web.RequestHandler.get`.\n\n        `open` may be a coroutine. `on_message` will not be called until\n        `open` has returned.\n\n        .. versionchanged:: 5.1\n\n           ``open`` may be a coroutine.\n        \"\"\"\n        pass\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        \"\"\"Handle incoming messages on the WebSocket\n\n        This method must be overridden.\n\n        .. versionchanged:: 4.5\n\n           ``on_message`` can be a coroutine.\n        \"\"\"\n        raise NotImplementedError\n\n    def ping(self, data: Union[str, bytes] = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``websocket_ping_interval`` application\n        setting instead of sending pings manually.\n\n        .. versionchanged:: 5.1\n\n           The data argument is now optional.\n\n        \"\"\"\n        data = utf8(data)\n        if self.ws_connection is None or self.ws_connection.is_closing():\n            raise WebSocketClosedError()\n        self.ws_connection.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        \"\"\"Invoked when the response to a ping frame is received.\"\"\"\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        \"\"\"Invoked when the a ping frame is received.\"\"\"\n        pass\n\n    def on_close(self) -> None:\n        \"\"\"Invoked when the WebSocket is closed.\n\n        If the connection was closed cleanly and a status code or reason\n        phrase was supplied, these values will be available as the attributes\n        ``self.close_code`` and ``self.close_reason``.\n\n        .. versionchanged:: 4.0\n\n           Added ``close_code`` and ``close_reason`` attributes.\n        \"\"\"\n        pass\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes this Web Socket.\n\n        Once the close handshake is successful the socket will be closed.\n\n        ``code`` may be a numeric status code, taken from the values\n        defined in `RFC 6455 section 7.4.1\n        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.\n        ``reason`` may be a textual message about why the connection is\n        closing.  These values are made available to the client, but are\n        not otherwise interpreted by the websocket protocol.\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.ws_connection:\n            self.ws_connection.close(code, reason)\n            self.ws_connection = None\n\n    def check_origin(self, origin: str) -> bool:\n        \"\"\"Override to enable support for allowing alternate origins.\n\n        The ``origin`` argument is the value of the ``Origin`` HTTP\n        header, the url responsible for initiating this request.  This\n        method is not called for clients that do not send this header;\n        such requests are always allowed (because all browsers that\n        implement WebSockets support this header, and non-browser\n        clients do not have the same cross-site security concerns).\n\n        Should return ``True`` to accept the request or ``False`` to\n        reject it. By default, rejects all requests with an origin on\n        a host other than this one.\n\n        This is a security protection against cross site scripting attacks on\n        browsers, since WebSockets are allowed to bypass the usual same-origin\n        policies and don't use CORS headers.\n\n        .. warning::\n\n           This is an important security measure; don't disable it\n           without understanding the security implications. In\n           particular, if your authentication is cookie-based, you\n           must either restrict the origins allowed by\n           ``check_origin()`` or implement your own XSRF-like\n           protection for websocket connections. See `these\n           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_\n           `articles\n           <https://devcenter.heroku.com/articles/websocket-security>`_\n           for more.\n\n        To accept all cross-origin traffic (which was the default prior to\n        Tornado 4.0), simply override this method to always return ``True``::\n\n            def check_origin(self, origin):\n                return True\n\n        To allow connections from any subdomain of your site, you might\n        do something like::\n\n            def check_origin(self, origin):\n                parsed_origin = urllib.parse.urlparse(origin)\n                return parsed_origin.netloc.endswith(\".mydomain.com\")\n\n        .. versionadded:: 4.0\n\n        \"\"\"\n        parsed_origin = urlparse(origin)\n        origin = parsed_origin.netloc\n        origin = origin.lower()\n\n        host = self.request.headers.get(\"Host\")\n\n        # Check to see that origin matches host directly, including ports\n        return origin == host\n\n    def set_nodelay(self, value: bool) -> None:\n        \"\"\"Set the no-delay flag for this stream.\n\n        By default, small messages may be delayed and/or combined to minimize\n        the number of packets sent.  This can sometimes cause 200-500ms delays\n        due to the interaction between Nagle's algorithm and TCP delayed\n        ACKs.  To reduce this delay (at the expense of possibly increasing\n        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket\n        connection is established.\n\n        See `.BaseIOStream.set_nodelay` for additional details.\n\n        .. versionadded:: 3.1\n        \"\"\"\n        assert self.ws_connection is not None\n        self.ws_connection.set_nodelay(value)\n\n    def on_connection_close(self) -> None:\n        if self.ws_connection:\n            self.ws_connection.on_connection_close()\n            self.ws_connection = None\n        if not self._on_close_called:\n            self._on_close_called = True\n            self.on_close()\n            self._break_cycles()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _break_cycles(self) -> None:\n        # WebSocketHandlers call finish() early, but we don't want to\n        # break up reference cycles (which makes it impossible to call\n        # self.render_string) until after we've really closed the\n        # connection (if it was established in the first place,\n        # indicated by status code 101).\n        if self.get_status() != 101 or self._on_close_called:\n            super()._break_cycles()\n\n    def send_error(self, *args: Any, **kwargs: Any) -> None:\n        if self.stream is None:\n            super().send_error(*args, **kwargs)\n        else:\n            # If we get an uncaught exception during the handshake,\n            # we have no choice but to abruptly close the connection.\n            # TODO: for uncaught exceptions after the handshake,\n            # we can close the connection more gracefully.\n            self.stream.close()\n\n    def get_websocket_protocol(self) -> Optional[\"WebSocketProtocol\"]:\n        websocket_version = self.request.headers.get(\"Sec-WebSocket-Version\")\n        if websocket_version in (\"7\", \"8\", \"13\"):\n            params = _WebSocketParams(\n                ping_interval=self.ping_interval,\n                ping_timeout=self.ping_timeout,\n                max_message_size=self.max_message_size,\n                compression_options=self.get_compression_options(),\n            )\n            return WebSocketProtocol13(self, False, params)\n        return None\n\n    def _detach_stream(self) -> IOStream:\n        # disable non-WS methods\n        for method in [\n            \"write\",\n            \"redirect\",\n            \"set_header\",\n            \"set_cookie\",\n            \"set_status\",\n            \"flush\",\n            \"finish\",\n        ]:\n            setattr(self, method, _raise_not_supported_for_websockets)\n        return self.detach()\n\n\ndef _raise_not_supported_for_websockets(*args: Any, **kwargs: Any) -> None:\n    raise RuntimeError(\"Method not supported for Web Sockets\")\n\n\nclass WebSocketProtocol(abc.ABC):\n    \"\"\"Base class for WebSocket protocol versions.\n    \"\"\"\n\n    def __init__(self, handler: \"_WebSocketDelegate\") -> None:\n        self.handler = handler\n        self.stream = None  # type: Optional[IOStream]\n        self.client_terminated = False\n        self.server_terminated = False\n\n    def _run_callback(\n        self, callback: Callable, *args: Any, **kwargs: Any\n    ) -> \"Optional[Future[Any]]\":\n        \"\"\"Runs the given callback with exception handling.\n\n        If the callback is a coroutine, returns its Future. On error, aborts the\n        websocket connection and returns None.\n        \"\"\"\n        try:\n            result = callback(*args, **kwargs)\n        except Exception:\n            self.handler.log_exception(*sys.exc_info())\n            self._abort()\n            return None\n        else:\n            if result is not None:\n                result = gen.convert_yielded(result)\n                assert self.stream is not None\n                self.stream.io_loop.add_future(result, lambda f: f.result())\n            return result\n\n    def on_connection_close(self) -> None:\n        self._abort()\n\n    def _abort(self) -> None:\n        \"\"\"Instantly aborts the WebSocket connection by closing the socket\"\"\"\n        self.client_terminated = True\n        self.server_terminated = True\n        if self.stream is not None:\n            self.stream.close()  # forcibly tear down the connection\n        self.close()  # let the subclass cleanup\n\n    @abc.abstractmethod\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def is_closing(self) -> bool:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        raise NotImplementedError()\n\n    @property\n    @abc.abstractmethod\n    def selected_subprotocol(self) -> Optional[str]:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def write_ping(self, data: bytes) -> None:\n        raise NotImplementedError()\n\n    # The entry points below are used by WebSocketClientConnection,\n    # which was introduced after we only supported a single version of\n    # WebSocketProtocol. The WebSocketProtocol/WebSocketProtocol13\n    # boundary is currently pretty ad-hoc.\n    @abc.abstractmethod\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def start_pinging(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    async def _receive_frame_loop(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def set_nodelay(self, x: bool) -> None:\n        raise NotImplementedError()\n\n\nclass _PerMessageDeflateCompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        # There is no symbolic constant for the minimum wbits value.\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n\n        if (\n            compression_options is None\n            or \"compression_level\" not in compression_options\n        ):\n            self._compression_level = tornado.web.GZipContentEncoding.GZIP_LEVEL\n        else:\n            self._compression_level = compression_options[\"compression_level\"]\n\n        if compression_options is None or \"mem_level\" not in compression_options:\n            self._mem_level = 8\n        else:\n            self._mem_level = compression_options[\"mem_level\"]\n\n        if persistent:\n            self._compressor = self._create_compressor()  # type: Optional[_Compressor]\n        else:\n            self._compressor = None\n\n    def _create_compressor(self) -> \"_Compressor\":\n        return zlib.compressobj(\n            self._compression_level, zlib.DEFLATED, -self._max_wbits, self._mem_level\n        )\n\n    def compress(self, data: bytes) -> bytes:\n        compressor = self._compressor or self._create_compressor()\n        data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)\n        assert data.endswith(b\"\\x00\\x00\\xff\\xff\")\n        return data[:-4]\n\n\nclass _PerMessageDeflateDecompressor(object):\n    def __init__(\n        self,\n        persistent: bool,\n        max_wbits: Optional[int],\n        max_message_size: int,\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        self._max_message_size = max_message_size\n        if max_wbits is None:\n            max_wbits = zlib.MAX_WBITS\n        if not (8 <= max_wbits <= zlib.MAX_WBITS):\n            raise ValueError(\n                \"Invalid max_wbits value %r; allowed range 8-%d\",\n                max_wbits,\n                zlib.MAX_WBITS,\n            )\n        self._max_wbits = max_wbits\n        if persistent:\n            self._decompressor = (\n                self._create_decompressor()\n            )  # type: Optional[_Decompressor]\n        else:\n            self._decompressor = None\n\n    def _create_decompressor(self) -> \"_Decompressor\":\n        return zlib.decompressobj(-self._max_wbits)\n\n    def decompress(self, data: bytes) -> bytes:\n        decompressor = self._decompressor or self._create_decompressor()\n        result = decompressor.decompress(\n            data + b\"\\x00\\x00\\xff\\xff\", self._max_message_size\n        )\n        if decompressor.unconsumed_tail:\n            raise _DecompressTooLargeError()\n        return result\n\n\nclass WebSocketProtocol13(WebSocketProtocol):\n    \"\"\"Implementation of the WebSocket protocol from RFC 6455.\n\n    This class supports versions 7 and 8 of the protocol in addition to the\n    final version 13.\n    \"\"\"\n\n    # Bit masks for the first byte of a frame.\n    FIN = 0x80\n    RSV1 = 0x40\n    RSV2 = 0x20\n    RSV3 = 0x10\n    RSV_MASK = RSV1 | RSV2 | RSV3\n    OPCODE_MASK = 0x0F\n\n    stream = None  # type: IOStream\n\n    def __init__(\n        self,\n        handler: \"_WebSocketDelegate\",\n        mask_outgoing: bool,\n        params: _WebSocketParams,\n    ) -> None:\n        WebSocketProtocol.__init__(self, handler)\n        self.mask_outgoing = mask_outgoing\n        self.params = params\n        self._final_frame = False\n        self._frame_opcode = None\n        self._masked_frame = None\n        self._frame_mask = None  # type: Optional[bytes]\n        self._frame_length = None\n        self._fragmented_message_buffer = None  # type: Optional[bytes]\n        self._fragmented_message_opcode = None\n        self._waiting = None  # type: object\n        self._compression_options = params.compression_options\n        self._decompressor = None  # type: Optional[_PerMessageDeflateDecompressor]\n        self._compressor = None  # type: Optional[_PerMessageDeflateCompressor]\n        self._frame_compressed = None  # type: Optional[bool]\n        # The total uncompressed size of all messages received or sent.\n        # Unicode messages are encoded to utf8.\n        # Only for testing; subject to change.\n        self._message_bytes_in = 0\n        self._message_bytes_out = 0\n        # The total size of all packets received or sent.  Includes\n        # the effect of compression, frame overhead, and control frames.\n        self._wire_bytes_in = 0\n        self._wire_bytes_out = 0\n        self.ping_callback = None  # type: Optional[PeriodicCallback]\n        self.last_ping = 0.0\n        self.last_pong = 0.0\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n\n    # Use a property for this to satisfy the abc.\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        return self._selected_subprotocol\n\n    @selected_subprotocol.setter\n    def selected_subprotocol(self, value: Optional[str]) -> None:\n        self._selected_subprotocol = value\n\n    async def accept_connection(self, handler: WebSocketHandler) -> None:\n        try:\n            self._handle_websocket_headers(handler)\n        except ValueError:\n            handler.set_status(400)\n            log_msg = \"Missing/Invalid WebSocket headers\"\n            handler.finish(log_msg)\n            gen_log.debug(log_msg)\n            return\n\n        try:\n            await self._accept_connection(handler)\n        except asyncio.CancelledError:\n            self._abort()\n            return\n        except ValueError:\n            gen_log.debug(\"Malformed WebSocket request received\", exc_info=True)\n            self._abort()\n            return\n\n    def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:\n        \"\"\"Verifies all invariant- and required headers\n\n        If a header is missing or have an incorrect value ValueError will be\n        raised\n        \"\"\"\n        fields = (\"Host\", \"Sec-Websocket-Key\", \"Sec-Websocket-Version\")\n        if not all(map(lambda f: handler.request.headers.get(f), fields)):\n            raise ValueError(\"Missing/Invalid WebSocket headers\")\n\n    @staticmethod\n    def compute_accept_value(key: Union[str, bytes]) -> str:\n        \"\"\"Computes the value for the Sec-WebSocket-Accept header,\n        given the value for Sec-WebSocket-Key.\n        \"\"\"\n        sha1 = hashlib.sha1()\n        sha1.update(utf8(key))\n        sha1.update(b\"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\")  # Magic value\n        return native_str(base64.b64encode(sha1.digest()))\n\n    def _challenge_response(self, handler: WebSocketHandler) -> str:\n        return WebSocketProtocol13.compute_accept_value(\n            cast(str, handler.request.headers.get(\"Sec-Websocket-Key\"))\n        )\n\n    async def _accept_connection(self, handler: WebSocketHandler) -> None:\n        subprotocol_header = handler.request.headers.get(\"Sec-WebSocket-Protocol\")\n        if subprotocol_header:\n            subprotocols = [s.strip() for s in subprotocol_header.split(\",\")]\n        else:\n            subprotocols = []\n        self.selected_subprotocol = handler.select_subprotocol(subprotocols)\n        if self.selected_subprotocol:\n            assert self.selected_subprotocol in subprotocols\n            handler.set_header(\"Sec-WebSocket-Protocol\", self.selected_subprotocol)\n\n        extensions = self._parse_extensions_header(handler.request.headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                # TODO: negotiate parameters if compression_options\n                # specifies limits.\n                self._create_compressors(\"server\", ext[1], self._compression_options)\n                if (\n                    \"client_max_window_bits\" in ext[1]\n                    and ext[1][\"client_max_window_bits\"] is None\n                ):\n                    # Don't echo an offered client_max_window_bits\n                    # parameter with no value.\n                    del ext[1][\"client_max_window_bits\"]\n                handler.set_header(\n                    \"Sec-WebSocket-Extensions\",\n                    httputil._encode_header(\"permessage-deflate\", ext[1]),\n                )\n                break\n\n        handler.clear_header(\"Content-Type\")\n        handler.set_status(101)\n        handler.set_header(\"Upgrade\", \"websocket\")\n        handler.set_header(\"Connection\", \"Upgrade\")\n        handler.set_header(\"Sec-WebSocket-Accept\", self._challenge_response(handler))\n        handler.finish()\n\n        self.stream = handler._detach_stream()\n\n        self.start_pinging()\n        try:\n            open_result = handler.open(*handler.open_args, **handler.open_kwargs)\n            if open_result is not None:\n                await open_result\n        except Exception:\n            handler.log_exception(*sys.exc_info())\n            self._abort()\n            return\n\n        await self._receive_frame_loop()\n\n    def _parse_extensions_header(\n        self, headers: httputil.HTTPHeaders\n    ) -> List[Tuple[str, Dict[str, str]]]:\n        extensions = headers.get(\"Sec-WebSocket-Extensions\", \"\")\n        if extensions:\n            return [httputil._parse_header(e.strip()) for e in extensions.split(\",\")]\n        return []\n\n    def _process_server_headers(\n        self, key: Union[str, bytes], headers: httputil.HTTPHeaders\n    ) -> None:\n        \"\"\"Process the headers sent by the server to this client connection.\n\n        'key' is the websocket handshake challenge/response key.\n        \"\"\"\n        assert headers[\"Upgrade\"].lower() == \"websocket\"\n        assert headers[\"Connection\"].lower() == \"upgrade\"\n        accept = self.compute_accept_value(key)\n        assert headers[\"Sec-Websocket-Accept\"] == accept\n\n        extensions = self._parse_extensions_header(headers)\n        for ext in extensions:\n            if ext[0] == \"permessage-deflate\" and self._compression_options is not None:\n                self._create_compressors(\"client\", ext[1])\n            else:\n                raise ValueError(\"unsupported extension %r\", ext)\n\n        self.selected_subprotocol = headers.get(\"Sec-WebSocket-Protocol\", None)\n\n    def _get_compressor_options(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Converts a websocket agreed_parameters set to keyword arguments\n        for our compressor objects.\n        \"\"\"\n        options = dict(\n            persistent=(side + \"_no_context_takeover\") not in agreed_parameters\n        )  # type: Dict[str, Any]\n        wbits_header = agreed_parameters.get(side + \"_max_window_bits\", None)\n        if wbits_header is None:\n            options[\"max_wbits\"] = zlib.MAX_WBITS\n        else:\n            options[\"max_wbits\"] = int(wbits_header)\n        options[\"compression_options\"] = compression_options\n        return options\n\n    def _create_compressors(\n        self,\n        side: str,\n        agreed_parameters: Dict[str, Any],\n        compression_options: Optional[Dict[str, Any]] = None,\n    ) -> None:\n        # TODO: handle invalid parameters gracefully\n        allowed_keys = set(\n            [\n                \"server_no_context_takeover\",\n                \"client_no_context_takeover\",\n                \"server_max_window_bits\",\n                \"client_max_window_bits\",\n            ]\n        )\n        for key in agreed_parameters:\n            if key not in allowed_keys:\n                raise ValueError(\"unsupported compression parameter %r\" % key)\n        other_side = \"client\" if (side == \"server\") else \"server\"\n        self._compressor = _PerMessageDeflateCompressor(\n            **self._get_compressor_options(side, agreed_parameters, compression_options)\n        )\n        self._decompressor = _PerMessageDeflateDecompressor(\n            max_message_size=self.params.max_message_size,\n            **self._get_compressor_options(\n                other_side, agreed_parameters, compression_options\n            )\n        )\n\n    def _write_frame(\n        self, fin: bool, opcode: int, data: bytes, flags: int = 0\n    ) -> \"Future[None]\":\n        data_len = len(data)\n        if opcode & 0x8:\n            # All control frames MUST have a payload length of 125\n            # bytes or less and MUST NOT be fragmented.\n            if not fin:\n                raise ValueError(\"control frames may not be fragmented\")\n            if data_len > 125:\n                raise ValueError(\"control frame payloads may not exceed 125 bytes\")\n        if fin:\n            finbit = self.FIN\n        else:\n            finbit = 0\n        frame = struct.pack(\"B\", finbit | opcode | flags)\n        if self.mask_outgoing:\n            mask_bit = 0x80\n        else:\n            mask_bit = 0\n        if data_len < 126:\n            frame += struct.pack(\"B\", data_len | mask_bit)\n        elif data_len <= 0xFFFF:\n            frame += struct.pack(\"!BH\", 126 | mask_bit, data_len)\n        else:\n            frame += struct.pack(\"!BQ\", 127 | mask_bit, data_len)\n        if self.mask_outgoing:\n            mask = os.urandom(4)\n            data = mask + _websocket_mask(mask, data)\n        frame += data\n        self._wire_bytes_out += len(frame)\n        return self.stream.write(frame)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends the given message to the client of this Web Socket.\"\"\"\n        if binary:\n            opcode = 0x2\n        else:\n            opcode = 0x1\n        message = tornado.escape.utf8(message)\n        assert isinstance(message, bytes)\n        self._message_bytes_out += len(message)\n        flags = 0\n        if self._compressor:\n            message = self._compressor.compress(message)\n            flags |= self.RSV1\n        # For historical reasons, write methods in Tornado operate in a semi-synchronous\n        # mode in which awaiting the Future they return is optional (But errors can\n        # still be raised). This requires us to go through an awkward dance here\n        # to transform the errors that may be returned while presenting the same\n        # semi-synchronous interface.\n        try:\n            fut = self._write_frame(True, opcode, message, flags=flags)\n        except StreamClosedError:\n            raise WebSocketClosedError()\n\n        async def wrapper() -> None:\n            try:\n                await fut\n            except StreamClosedError:\n                raise WebSocketClosedError()\n\n        return asyncio.ensure_future(wrapper())\n\n    def write_ping(self, data: bytes) -> None:\n        \"\"\"Send ping frame.\"\"\"\n        assert isinstance(data, bytes)\n        self._write_frame(True, 0x9, data)\n\n    async def _receive_frame_loop(self) -> None:\n        try:\n            while not self.client_terminated:\n                await self._receive_frame()\n        except StreamClosedError:\n            self._abort()\n        self.handler.on_ws_connection_close(self.close_code, self.close_reason)\n\n    async def _read_bytes(self, n: int) -> bytes:\n        data = await self.stream.read_bytes(n)\n        self._wire_bytes_in += n\n        return data\n\n    async def _receive_frame(self) -> None:\n        # Read the frame header.\n        data = await self._read_bytes(2)\n        header, mask_payloadlen = struct.unpack(\"BB\", data)\n        is_final_frame = header & self.FIN\n        reserved_bits = header & self.RSV_MASK\n        opcode = header & self.OPCODE_MASK\n        opcode_is_control = opcode & 0x8\n        if self._decompressor is not None and opcode != 0:\n            # Compression flag is present in the first frame's header,\n            # but we can't decompress until we have all the frames of\n            # the message.\n            self._frame_compressed = bool(reserved_bits & self.RSV1)\n            reserved_bits &= ~self.RSV1\n        if reserved_bits:\n            # client is using as-yet-undefined extensions; abort\n            self._abort()\n            return\n        is_masked = bool(mask_payloadlen & 0x80)\n        payloadlen = mask_payloadlen & 0x7F\n\n        # Parse and validate the length.\n        if opcode_is_control and payloadlen >= 126:\n            # control frames must have payload < 126\n            self._abort()\n            return\n        if payloadlen < 126:\n            self._frame_length = payloadlen\n        elif payloadlen == 126:\n            data = await self._read_bytes(2)\n            payloadlen = struct.unpack(\"!H\", data)[0]\n        elif payloadlen == 127:\n            data = await self._read_bytes(8)\n            payloadlen = struct.unpack(\"!Q\", data)[0]\n        new_len = payloadlen\n        if self._fragmented_message_buffer is not None:\n            new_len += len(self._fragmented_message_buffer)\n        if new_len > self.params.max_message_size:\n            self.close(1009, \"message too big\")\n            self._abort()\n            return\n\n        # Read the payload, unmasking if necessary.\n        if is_masked:\n            self._frame_mask = await self._read_bytes(4)\n        data = await self._read_bytes(payloadlen)\n        if is_masked:\n            assert self._frame_mask is not None\n            data = _websocket_mask(self._frame_mask, data)\n\n        # Decide what to do with this frame.\n        if opcode_is_control:\n            # control frames may be interleaved with a series of fragmented\n            # data frames, so control frames must not interact with\n            # self._fragmented_*\n            if not is_final_frame:\n                # control frames must not be fragmented\n                self._abort()\n                return\n        elif opcode == 0:  # continuation frame\n            if self._fragmented_message_buffer is None:\n                # nothing to continue\n                self._abort()\n                return\n            self._fragmented_message_buffer += data\n            if is_final_frame:\n                opcode = self._fragmented_message_opcode\n                data = self._fragmented_message_buffer\n                self._fragmented_message_buffer = None\n        else:  # start of new data message\n            if self._fragmented_message_buffer is not None:\n                # can't start new message until the old one is finished\n                self._abort()\n                return\n            if not is_final_frame:\n                self._fragmented_message_opcode = opcode\n                self._fragmented_message_buffer = data\n\n        if is_final_frame:\n            handled_future = self._handle_message(opcode, data)\n            if handled_future is not None:\n                await handled_future\n\n    def _handle_message(self, opcode: int, data: bytes) -> \"Optional[Future[None]]\":\n        \"\"\"Execute on_message, returning its Future if it is a coroutine.\"\"\"\n        if self.client_terminated:\n            return None\n\n        if self._frame_compressed:\n            assert self._decompressor is not None\n            try:\n                data = self._decompressor.decompress(data)\n            except _DecompressTooLargeError:\n                self.close(1009, \"message too big after decompression\")\n                self._abort()\n                return None\n\n        if opcode == 0x1:\n            # UTF-8 data\n            self._message_bytes_in += len(data)\n            try:\n                decoded = data.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                self._abort()\n                return None\n            return self._run_callback(self.handler.on_message, decoded)\n        elif opcode == 0x2:\n            # Binary data\n            self._message_bytes_in += len(data)\n            return self._run_callback(self.handler.on_message, data)\n        elif opcode == 0x8:\n            # Close\n            self.client_terminated = True\n            if len(data) >= 2:\n                self.close_code = struct.unpack(\">H\", data[:2])[0]\n            if len(data) > 2:\n                self.close_reason = to_unicode(data[2:])\n            # Echo the received close code, if any (RFC 6455 section 5.5.1).\n            self.close(self.close_code)\n        elif opcode == 0x9:\n            # Ping\n            try:\n                self._write_frame(True, 0xA, data)\n            except StreamClosedError:\n                self._abort()\n            self._run_callback(self.handler.on_ping, data)\n        elif opcode == 0xA:\n            # Pong\n            self.last_pong = IOLoop.current().time()\n            return self._run_callback(self.handler.on_pong, data)\n        else:\n            self._abort()\n        return None\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the WebSocket connection.\"\"\"\n        if not self.server_terminated:\n            if not self.stream.closed():\n                if code is None and reason is not None:\n                    code = 1000  # \"normal closure\" status code\n                if code is None:\n                    close_data = b\"\"\n                else:\n                    close_data = struct.pack(\">H\", code)\n                if reason is not None:\n                    close_data += utf8(reason)\n                try:\n                    self._write_frame(True, 0x8, close_data)\n                except StreamClosedError:\n                    self._abort()\n            self.server_terminated = True\n        if self.client_terminated:\n            if self._waiting is not None:\n                self.stream.io_loop.remove_timeout(self._waiting)\n                self._waiting = None\n            self.stream.close()\n        elif self._waiting is None:\n            # Give the client a few seconds to complete a clean shutdown,\n            # otherwise just close the connection.\n            self._waiting = self.stream.io_loop.add_timeout(\n                self.stream.io_loop.time() + 5, self._abort\n            )\n        if self.ping_callback:\n            self.ping_callback.stop()\n            self.ping_callback = None\n\n    def is_closing(self) -> bool:\n        \"\"\"Return ``True`` if this connection is closing.\n\n        The connection is considered closing if either side has\n        initiated its closing handshake or if the stream has been\n        shut down uncleanly.\n        \"\"\"\n        return self.stream.closed() or self.client_terminated or self.server_terminated\n\n    @property\n    def ping_interval(self) -> Optional[float]:\n        interval = self.params.ping_interval\n        if interval is not None:\n            return interval\n        return 0\n\n    @property\n    def ping_timeout(self) -> Optional[float]:\n        timeout = self.params.ping_timeout\n        if timeout is not None:\n            return timeout\n        assert self.ping_interval is not None\n        return max(3 * self.ping_interval, 30)\n\n    def start_pinging(self) -> None:\n        \"\"\"Start sending periodic pings to keep the connection alive\"\"\"\n        assert self.ping_interval is not None\n        if self.ping_interval > 0:\n            self.last_ping = self.last_pong = IOLoop.current().time()\n            self.ping_callback = PeriodicCallback(\n                self.periodic_ping, self.ping_interval * 1000\n            )\n            self.ping_callback.start()\n\n    def periodic_ping(self) -> None:\n        \"\"\"Send a ping to keep the websocket alive\n\n        Called periodically if the websocket_ping_interval is set and non-zero.\n        \"\"\"\n        if self.is_closing() and self.ping_callback is not None:\n            self.ping_callback.stop()\n            return\n\n        # Check for timeout on pong. Make sure that we really have\n        # sent a recent ping in case the machine with both server and\n        # client has been suspended since the last ping.\n        now = IOLoop.current().time()\n        since_last_pong = now - self.last_pong\n        since_last_ping = now - self.last_ping\n        assert self.ping_interval is not None\n        assert self.ping_timeout is not None\n        if (\n            since_last_ping < 2 * self.ping_interval\n            and since_last_pong > self.ping_timeout\n        ):\n            self.close()\n            return\n\n        self.write_ping(b\"\")\n        self.last_ping = now\n\n    def set_nodelay(self, x: bool) -> None:\n        self.stream.set_nodelay(x)\n\n\nclass WebSocketClientConnection(simple_httpclient._HTTPConnection):\n    \"\"\"WebSocket client connection.\n\n    This class should not be instantiated directly; use the\n    `websocket_connect` function instead.\n    \"\"\"\n\n    protocol = None  # type: WebSocketProtocol\n\n    def __init__(\n        self,\n        request: httpclient.HTTPRequest,\n        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n        compression_options: Optional[Dict[str, Any]] = None,\n        ping_interval: Optional[float] = None,\n        ping_timeout: Optional[float] = None,\n        max_message_size: int = _default_max_message_size,\n        subprotocols: Optional[List[str]] = [],\n    ) -> None:\n        self.connect_future = Future()  # type: Future[WebSocketClientConnection]\n        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]\n        self.key = base64.b64encode(os.urandom(16))\n        self._on_message_callback = on_message_callback\n        self.close_code = None  # type: Optional[int]\n        self.close_reason = None  # type: Optional[str]\n        self.params = _WebSocketParams(\n            ping_interval=ping_interval,\n            ping_timeout=ping_timeout,\n            max_message_size=max_message_size,\n            compression_options=compression_options,\n        )\n\n        scheme, sep, rest = request.url.partition(\":\")\n        scheme = {\"ws\": \"http\", \"wss\": \"https\"}[scheme]\n        request.url = scheme + sep + rest\n        request.headers.update(\n            {\n                \"Upgrade\": \"websocket\",\n                \"Connection\": \"Upgrade\",\n                \"Sec-WebSocket-Key\": self.key,\n                \"Sec-WebSocket-Version\": \"13\",\n            }\n        )\n        if subprotocols is not None:\n            request.headers[\"Sec-WebSocket-Protocol\"] = \",\".join(subprotocols)\n        if compression_options is not None:\n            # Always offer to let the server set our max_wbits (and even though\n            # we don't offer it, we will accept a client_no_context_takeover\n            # from the server).\n            # TODO: set server parameters for deflate extension\n            # if requested in self.compression_options.\n            request.headers[\n                \"Sec-WebSocket-Extensions\"\n            ] = \"permessage-deflate; client_max_window_bits\"\n\n        self.tcp_client = TCPClient()\n        super().__init__(\n            None,\n            request,\n            lambda: None,\n            self._on_http_response,\n            104857600,\n            self.tcp_client,\n            65536,\n            104857600,\n        )\n\n    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:\n        \"\"\"Closes the websocket connection.\n\n        ``code`` and ``reason`` are documented under\n        `WebSocketHandler.close`.\n\n        .. versionadded:: 3.2\n\n        .. versionchanged:: 4.0\n\n           Added the ``code`` and ``reason`` arguments.\n        \"\"\"\n        if self.protocol is not None:\n            self.protocol.close(code, reason)\n            self.protocol = None  # type: ignore\n\n    def on_connection_close(self) -> None:\n        if not self.connect_future.done():\n            self.connect_future.set_exception(StreamClosedError())\n        self._on_message(None)\n        self.tcp_client.close()\n        super().on_connection_close()\n\n    def on_ws_connection_close(\n        self, close_code: Optional[int] = None, close_reason: Optional[str] = None\n    ) -> None:\n        self.close_code = close_code\n        self.close_reason = close_reason\n        self.on_connection_close()\n\n    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:\n        if not self.connect_future.done():\n            if response.error:\n                self.connect_future.set_exception(response.error)\n            else:\n                self.connect_future.set_exception(\n                    WebSocketError(\"Non-websocket response\")\n                )\n\n    async def headers_received(\n        self,\n        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],\n        headers: httputil.HTTPHeaders,\n    ) -> None:\n        assert isinstance(start_line, httputil.ResponseStartLine)\n        if start_line.code != 101:\n            await super().headers_received(start_line, headers)\n            return\n\n        if self._timeout is not None:\n            self.io_loop.remove_timeout(self._timeout)\n            self._timeout = None\n\n        self.headers = headers\n        self.protocol = self.get_websocket_protocol()\n        self.protocol._process_server_headers(self.key, self.headers)\n        self.protocol.stream = self.connection.detach()\n\n        IOLoop.current().add_callback(self.protocol._receive_frame_loop)\n        self.protocol.start_pinging()\n\n        # Once we've taken over the connection, clear the final callback\n        # we set on the http request.  This deactivates the error handling\n        # in simple_httpclient that would otherwise interfere with our\n        # ability to see exceptions.\n        self.final_callback = None  # type: ignore\n\n        future_set_result_unless_cancelled(self.connect_future, self)\n\n    def write_message(\n        self, message: Union[str, bytes], binary: bool = False\n    ) -> \"Future[None]\":\n        \"\"\"Sends a message to the WebSocket server.\n\n        If the stream is closed, raises `WebSocketClosedError`.\n        Returns a `.Future` which can be used for flow control.\n\n        .. versionchanged:: 5.0\n           Exception raised on a closed stream changed from `.StreamClosedError`\n           to `WebSocketClosedError`.\n        \"\"\"\n        return self.protocol.write_message(message, binary=binary)\n\n    def read_message(\n        self,\n        callback: Optional[Callable[[\"Future[Union[None, str, bytes]]\"], None]] = None,\n    ) -> Awaitable[Union[None, str, bytes]]:\n        \"\"\"Reads a message from the WebSocket server.\n\n        If on_message_callback was specified at WebSocket\n        initialization, this function will never return messages\n\n        Returns a future whose result is the message, or None\n        if the connection is closed.  If a callback argument\n        is given it will be called with the future when it is\n        ready.\n        \"\"\"\n\n        awaitable = self.read_queue.get()\n        if callback is not None:\n            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)\n        return awaitable\n\n    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:\n        return self._on_message(message)\n\n    def _on_message(\n        self, message: Union[None, str, bytes]\n    ) -> Optional[Awaitable[None]]:\n        if self._on_message_callback:\n            self._on_message_callback(message)\n            return None\n        else:\n            return self.read_queue.put(message)\n\n    def ping(self, data: bytes = b\"\") -> None:\n        \"\"\"Send ping frame to the remote end.\n\n        The data argument allows a small amount of data (up to 125\n        bytes) to be sent as a part of the ping message. Note that not\n        all websocket implementations expose this data to\n        applications.\n\n        Consider using the ``ping_interval`` argument to\n        `websocket_connect` instead of sending pings manually.\n\n        .. versionadded:: 5.1\n\n        \"\"\"\n        data = utf8(data)\n        if self.protocol is None:\n            raise WebSocketClosedError()\n        self.protocol.write_ping(data)\n\n    def on_pong(self, data: bytes) -> None:\n        pass\n\n    def on_ping(self, data: bytes) -> None:\n        pass\n\n    def get_websocket_protocol(self) -> WebSocketProtocol:\n        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)\n\n    @property\n    def selected_subprotocol(self) -> Optional[str]:\n        \"\"\"The subprotocol selected by the server.\n\n        .. versionadded:: 5.1\n        \"\"\"\n        return self.protocol.selected_subprotocol\n\n    def log_exception(\n        self,\n        typ: \"Optional[Type[BaseException]]\",\n        value: Optional[BaseException],\n        tb: Optional[TracebackType],\n    ) -> None:\n        assert typ is not None\n        assert value is not None\n        app_log.error(\"Uncaught exception %s\", value, exc_info=(typ, value, tb))\n\n\ndef websocket_connect(\n    url: Union[str, httpclient.HTTPRequest],\n    callback: Optional[Callable[[\"Future[WebSocketClientConnection]\"], None]] = None,\n    connect_timeout: Optional[float] = None,\n    on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,\n    compression_options: Optional[Dict[str, Any]] = None,\n    ping_interval: Optional[float] = None,\n    ping_timeout: Optional[float] = None,\n    max_message_size: int = _default_max_message_size,\n    subprotocols: Optional[List[str]] = None,\n) -> \"Awaitable[WebSocketClientConnection]\":\n    \"\"\"Client-side websocket support.\n\n    Takes a url and returns a Future whose result is a\n    `WebSocketClientConnection`.\n\n    ``compression_options`` is interpreted in the same way as the\n    return value of `.WebSocketHandler.get_compression_options`.\n\n    The connection supports two styles of operation. In the coroutine\n    style, the application typically calls\n    `~.WebSocketClientConnection.read_message` in a loop::\n\n        conn = yield websocket_connect(url)\n        while True:\n            msg = yield conn.read_message()\n            if msg is None: break\n            # Do something with msg\n\n    In the callback style, pass an ``on_message_callback`` to\n    ``websocket_connect``. In both styles, a message of ``None``\n    indicates that the connection has been closed.\n\n    ``subprotocols`` may be a list of strings specifying proposed\n    subprotocols. The selected protocol may be found on the\n    ``selected_subprotocol`` attribute of the connection object\n    when the connection is complete.\n\n    .. versionchanged:: 3.2\n       Also accepts ``HTTPRequest`` objects in place of urls.\n\n    .. versionchanged:: 4.1\n       Added ``compression_options`` and ``on_message_callback``.\n\n    .. versionchanged:: 4.5\n       Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size``\n       arguments, which have the same meaning as in `WebSocketHandler`.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.1\n       Added the ``subprotocols`` argument.\n    \"\"\"\n    if isinstance(url, httpclient.HTTPRequest):\n        assert connect_timeout is None\n        request = url\n        # Copy and convert the headers dict/object (see comments in\n        # AsyncHTTPClient.fetch)\n        request.headers = httputil.HTTPHeaders(request.headers)\n    else:\n        request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)\n    request = cast(\n        httpclient.HTTPRequest,\n        httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS),\n    )\n    conn = WebSocketClientConnection(\n        request,\n        on_message_callback=on_message_callback,\n        compression_options=compression_options,\n        ping_interval=ping_interval,\n        ping_timeout=ping_timeout,\n        max_message_size=max_message_size,\n        subprotocols=subprotocols,\n    )\n    if callback is not None:\n        IOLoop.current().add_future(conn.connect_future, callback)\n    return conn.connect_future\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]

**Title:** WebSocket Connections Follow Redirects Unexpectedly, Causing Timeout Errors

**Description:**
When attempting to establish a WebSocket connection to a URL that issues an HTTP redirect, the connection erroneously follows the redirect. This behavior is unintended for WebSocket communications and results in a timeout error because the redirected URL does not upgrade the connection to a WebSocket.

**Example Code:**
```python
from tornado.websocket import websocket_connect
from tornado.httpclient import HTTPError

# Attempting to connect to a WebSocket endpoint that redirects
try:
    ws = websocket_connect("/redirect")
except HTTPError as e:
    print(f"Connection failed with HTTP error code: {e.code}")
```

**Expected Behavior:**
The WebSocket connection should not follow HTTP redirects. Instead, it should immediately raise an error indicating that redirects are not supported for WebSocket connections.

**Actual Behavior:**
The WebSocket client follows the HTTP redirect, leading to a timeout after waiting for the connection to be established at the redirected URL.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/websocket.py
"""Implementation of the WebSocket protocol.

`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional
communication between the browser and server.

WebSockets are supported in the current versions of all major browsers,
although older versions that do not support WebSockets are still in use
(refer to http://caniuse.com/websockets for details).

This module implements the final version of the WebSocket protocol as
defined in `RFC 6455 <http://tools.ietf.org/html/rfc6455>`_.  Certain
browser versions (notably Safari 5.x) implemented an earlier draft of
the protocol (known as "draft 76") and are not compatible with this module.

.. versionchanged:: 4.0
   Removed support for the draft 76 protocol version.
"""

import abc
import asyncio
import base64
import hashlib
import os
import sys
import struct
import tornado.escape
import tornado.web
from urllib.parse import urlparse
import zlib

from tornado.concurrent import Future, future_set_result_unless_cancelled
from tornado.escape import utf8, native_str, to_unicode
from tornado import gen, httpclient, httputil
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.iostream import StreamClosedError, IOStream
from tornado.log import gen_log, app_log
from tornado import simple_httpclient
from tornado.queues import Queue
from tornado.tcpclient import TCPClient
from tornado.util import _websocket_mask

from typing import (
    TYPE_CHECKING,
    cast,
    Any,
    Optional,
    Dict,
    Union,
    List,
    Awaitable,
    Callable,
    Tuple,
    Type,
)
from types import TracebackType

if TYPE_CHECKING:
    from typing_extensions import Protocol

    # The zlib compressor types aren't actually exposed anywhere
    # publicly, so declare protocols for the portions we use.
    class _Compressor(Protocol):
        def compress(self, data: bytes) -> bytes:
            pass

        def flush(self, mode: int) -> bytes:
            pass

    class _Decompressor(Protocol):
        unconsumed_tail = b""  # type: bytes

        def decompress(self, data: bytes, max_length: int) -> bytes:
            pass

    class _WebSocketDelegate(Protocol):
        # The common base interface implemented by WebSocketHandler on
        # the server side and WebSocketClientConnection on the client
        # side.
        def on_ws_connection_close(
            self, close_code: Optional[int] = None, close_reason: Optional[str] = None
        ) -> None:
            pass

        def on_message(self, message: Union[str, bytes]) -> Optional["Awaitable[None]"]:
            pass

        def on_ping(self, data: bytes) -> None:
            pass

        def on_pong(self, data: bytes) -> None:
            pass

        def log_exception(
            self,
            typ: Optional[Type[BaseException]],
            value: Optional[BaseException],
            tb: Optional[TracebackType],
        ) -> None:
            pass


_default_max_message_size = 10 * 1024 * 1024


class WebSocketError(Exception):
    pass


class WebSocketClosedError(WebSocketError):
    """Raised by operations on a closed connection.

    .. versionadded:: 3.2
    """

    pass


class _DecompressTooLargeError(Exception):
    pass


class _WebSocketParams(object):
    def __init__(
        self,
        ping_interval: Optional[float] = None,
        ping_timeout: Optional[float] = None,
        max_message_size: int = _default_max_message_size,
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        self.ping_interval = ping_interval
        self.ping_timeout = ping_timeout
        self.max_message_size = max_message_size
        self.compression_options = compression_options


class WebSocketHandler(tornado.web.RequestHandler):
    """Subclass this class to create a basic WebSocket handler.

    Override `on_message` to handle incoming messages, and use
    `write_message` to send messages to the client. You can also
    override `open` and `on_close` to handle opened and closed
    connections.

    Custom upgrade response headers can be sent by overriding
    `~tornado.web.RequestHandler.set_default_headers` or
    `~tornado.web.RequestHandler.prepare`.

    See http://dev.w3.org/html5/websockets/ for details on the
    JavaScript interface.  The protocol is specified at
    http://tools.ietf.org/html/rfc6455.

    Here is an example WebSocket handler that echos back all received messages
    back to the client:

    .. testcode::

      class EchoWebSocket(tornado.websocket.WebSocketHandler):
          def open(self):
              print("WebSocket opened")

          def on_message(self, message):
              self.write_message(u"You said: " + message)

          def on_close(self):
              print("WebSocket closed")

    .. testoutput::
       :hide:

    WebSockets are not standard HTTP connections. The "handshake" is
    HTTP, but after the handshake, the protocol is
    message-based. Consequently, most of the Tornado HTTP facilities
    are not available in handlers of this type. The only communication
    methods available to you are `write_message()`, `ping()`, and
    `close()`. Likewise, your request handler class should implement
    `open()` method rather than ``get()`` or ``post()``.

    If you map the handler above to ``/websocket`` in your application, you can
    invoke it in JavaScript with::

      var ws = new WebSocket("ws://localhost:8888/websocket");
      ws.onopen = function() {
         ws.send("Hello, world");
      };
      ws.onmessage = function (evt) {
         alert(evt.data);
      };

    This script pops up an alert box that says "You said: Hello, world".

    Web browsers allow any site to open a websocket connection to any other,
    instead of using the same-origin policy that governs other network
    access from JavaScript.  This can be surprising and is a potential
    security hole, so since Tornado 4.0 `WebSocketHandler` requires
    applications that wish to receive cross-origin websockets to opt in
    by overriding the `~WebSocketHandler.check_origin` method (see that
    method's docs for details).  Failure to do so is the most likely
    cause of 403 errors when making a websocket connection.

    When using a secure websocket connection (``wss://``) with a self-signed
    certificate, the connection from a browser may fail because it wants
    to show the "accept this certificate" dialog but has nowhere to show it.
    You must first visit a regular HTML page using the same certificate
    to accept it before the websocket connection will succeed.

    If the application setting ``websocket_ping_interval`` has a non-zero
    value, a ping will be sent periodically, and the connection will be
    closed if a response is not received before the ``websocket_ping_timeout``.

    Messages larger than the ``websocket_max_message_size`` application setting
    (default 10MiB) will not be accepted.

    .. versionchanged:: 4.5
       Added ``websocket_ping_interval``, ``websocket_ping_timeout``, and
       ``websocket_max_message_size``.
    """

    def __init__(
        self,
        application: tornado.web.Application,
        request: httputil.HTTPServerRequest,
        **kwargs: Any
    ) -> None:
        super().__init__(application, request, **kwargs)
        self.ws_connection = None  # type: Optional[WebSocketProtocol]
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]
        self.stream = None  # type: Optional[IOStream]
        self._on_close_called = False

    async def get(self, *args: Any, **kwargs: Any) -> None:
        self.open_args = args
        self.open_kwargs = kwargs

        # Upgrade header should be present and should be equal to WebSocket
        if self.request.headers.get("Upgrade", "").lower() != "websocket":
            self.set_status(400)
            log_msg = 'Can "Upgrade" only to "WebSocket".'
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        # Connection header should be upgrade.
        # Some proxy servers/load balancers
        # might mess with it.
        headers = self.request.headers
        connection = map(
            lambda s: s.strip().lower(), headers.get("Connection", "").split(",")
        )
        if "upgrade" not in connection:
            self.set_status(400)
            log_msg = '"Connection" must be "Upgrade".'
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        # Handle WebSocket Origin naming convention differences
        # The difference between version 8 and 13 is that in 8 the
        # client sends a "Sec-Websocket-Origin" header and in 13 it's
        # simply "Origin".
        if "Origin" in self.request.headers:
            origin = self.request.headers.get("Origin")
        else:
            origin = self.request.headers.get("Sec-Websocket-Origin", None)

        # If there was an origin header, check to make sure it matches
        # according to check_origin. When the origin is None, we assume it
        # did not come from a browser and that it can be passed on.
        if origin is not None and not self.check_origin(origin):
            self.set_status(403)
            log_msg = "Cross origin websockets not allowed"
            self.finish(log_msg)
            gen_log.debug(log_msg)
            return

        self.ws_connection = self.get_websocket_protocol()
        if self.ws_connection:
            await self.ws_connection.accept_connection(self)
        else:
            self.set_status(426, "Upgrade Required")
            self.set_header("Sec-WebSocket-Version", "7, 8, 13")

    @property
    def ping_interval(self) -> Optional[float]:
        """The interval for websocket keep-alive pings.

        Set websocket_ping_interval = 0 to disable pings.
        """
        return self.settings.get("websocket_ping_interval", None)

    @property
    def ping_timeout(self) -> Optional[float]:
        """If no ping is received in this many seconds,
        close the websocket connection (VPNs, etc. can fail to cleanly close ws connections).
        Default is max of 3 pings or 30 seconds.
        """
        return self.settings.get("websocket_ping_timeout", None)

    @property
    def max_message_size(self) -> int:
        """Maximum allowed message size.

        If the remote peer sends a message larger than this, the connection
        will be closed.

        Default is 10MiB.
        """
        return self.settings.get(
            "websocket_max_message_size", _default_max_message_size
        )

    def write_message(
        self, message: Union[bytes, str, Dict[str, Any]], binary: bool = False
    ) -> "Future[None]":
        """Sends the given message to the client of this Web Socket.

        The message may be either a string or a dict (which will be
        encoded as json).  If the ``binary`` argument is false, the
        message will be sent as utf8; in binary mode any byte string
        is allowed.

        If the connection is already closed, raises `WebSocketClosedError`.
        Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 3.2
           `WebSocketClosedError` was added (previously a closed connection
           would raise an `AttributeError`)

        .. versionchanged:: 4.3
           Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 5.0
           Consistently raises `WebSocketClosedError`. Previously could
           sometimes raise `.StreamClosedError`.
        """
        if self.ws_connection is None or self.ws_connection.is_closing():
            raise WebSocketClosedError()
        if isinstance(message, dict):
            message = tornado.escape.json_encode(message)
        return self.ws_connection.write_message(message, binary=binary)

    def select_subprotocol(self, subprotocols: List[str]) -> Optional[str]:
        """Override to implement subprotocol negotiation.

        ``subprotocols`` is a list of strings identifying the
        subprotocols proposed by the client.  This method may be
        overridden to return one of those strings to select it, or
        ``None`` to not select a subprotocol.

        Failure to select a subprotocol does not automatically abort
        the connection, although clients may close the connection if
        none of their proposed subprotocols was selected.

        The list may be empty, in which case this method must return
        None. This method is always called exactly once even if no
        subprotocols were proposed so that the handler can be advised
        of this fact.

        .. versionchanged:: 5.1

           Previously, this method was called with a list containing
           an empty string instead of an empty list if no subprotocols
           were proposed by the client.
        """
        return None

    @property
    def selected_subprotocol(self) -> Optional[str]:
        """The subprotocol returned by `select_subprotocol`.

        .. versionadded:: 5.1
        """
        assert self.ws_connection is not None
        return self.ws_connection.selected_subprotocol

    def get_compression_options(self) -> Optional[Dict[str, Any]]:
        """Override to return compression options for the connection.

        If this method returns None (the default), compression will
        be disabled.  If it returns a dict (even an empty one), it
        will be enabled.  The contents of the dict may be used to
        control the following compression options:

        ``compression_level`` specifies the compression level.

        ``mem_level`` specifies the amount of memory used for the internal compression state.

         These parameters are documented in details here:
         https://docs.python.org/3.6/library/zlib.html#zlib.compressobj

        .. versionadded:: 4.1

        .. versionchanged:: 4.5

           Added ``compression_level`` and ``mem_level``.
        """
        # TODO: Add wbits option.
        return None

    def open(self, *args: str, **kwargs: str) -> Optional[Awaitable[None]]:
        """Invoked when a new WebSocket is opened.

        The arguments to `open` are extracted from the `tornado.web.URLSpec`
        regular expression, just like the arguments to
        `tornado.web.RequestHandler.get`.

        `open` may be a coroutine. `on_message` will not be called until
        `open` has returned.

        .. versionchanged:: 5.1

           ``open`` may be a coroutine.
        """
        pass

    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:
        """Handle incoming messages on the WebSocket

        This method must be overridden.

        .. versionchanged:: 4.5

           ``on_message`` can be a coroutine.
        """
        raise NotImplementedError

    def ping(self, data: Union[str, bytes] = b"") -> None:
        """Send ping frame to the remote end.

        The data argument allows a small amount of data (up to 125
        bytes) to be sent as a part of the ping message. Note that not
        all websocket implementations expose this data to
        applications.

        Consider using the ``websocket_ping_interval`` application
        setting instead of sending pings manually.

        .. versionchanged:: 5.1

           The data argument is now optional.

        """
        data = utf8(data)
        if self.ws_connection is None or self.ws_connection.is_closing():
            raise WebSocketClosedError()
        self.ws_connection.write_ping(data)

    def on_pong(self, data: bytes) -> None:
        """Invoked when the response to a ping frame is received."""
        pass

    def on_ping(self, data: bytes) -> None:
        """Invoked when the a ping frame is received."""
        pass

    def on_close(self) -> None:
        """Invoked when the WebSocket is closed.

        If the connection was closed cleanly and a status code or reason
        phrase was supplied, these values will be available as the attributes
        ``self.close_code`` and ``self.close_reason``.

        .. versionchanged:: 4.0

           Added ``close_code`` and ``close_reason`` attributes.
        """
        pass

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes this Web Socket.

        Once the close handshake is successful the socket will be closed.

        ``code`` may be a numeric status code, taken from the values
        defined in `RFC 6455 section 7.4.1
        <https://tools.ietf.org/html/rfc6455#section-7.4.1>`_.
        ``reason`` may be a textual message about why the connection is
        closing.  These values are made available to the client, but are
        not otherwise interpreted by the websocket protocol.

        .. versionchanged:: 4.0

           Added the ``code`` and ``reason`` arguments.
        """
        if self.ws_connection:
            self.ws_connection.close(code, reason)
            self.ws_connection = None

    def check_origin(self, origin: str) -> bool:
        """Override to enable support for allowing alternate origins.

        The ``origin`` argument is the value of the ``Origin`` HTTP
        header, the url responsible for initiating this request.  This
        method is not called for clients that do not send this header;
        such requests are always allowed (because all browsers that
        implement WebSockets support this header, and non-browser
        clients do not have the same cross-site security concerns).

        Should return ``True`` to accept the request or ``False`` to
        reject it. By default, rejects all requests with an origin on
        a host other than this one.

        This is a security protection against cross site scripting attacks on
        browsers, since WebSockets are allowed to bypass the usual same-origin
        policies and don't use CORS headers.

        .. warning::

           This is an important security measure; don't disable it
           without understanding the security implications. In
           particular, if your authentication is cookie-based, you
           must either restrict the origins allowed by
           ``check_origin()`` or implement your own XSRF-like
           protection for websocket connections. See `these
           <https://www.christian-schneider.net/CrossSiteWebSocketHijacking.html>`_
           `articles
           <https://devcenter.heroku.com/articles/websocket-security>`_
           for more.

        To accept all cross-origin traffic (which was the default prior to
        Tornado 4.0), simply override this method to always return ``True``::

            def check_origin(self, origin):
                return True

        To allow connections from any subdomain of your site, you might
        do something like::

            def check_origin(self, origin):
                parsed_origin = urllib.parse.urlparse(origin)
                return parsed_origin.netloc.endswith(".mydomain.com")

        .. versionadded:: 4.0

        """
        parsed_origin = urlparse(origin)
        origin = parsed_origin.netloc
        origin = origin.lower()

        host = self.request.headers.get("Host")

        # Check to see that origin matches host directly, including ports
        return origin == host

    def set_nodelay(self, value: bool) -> None:
        """Set the no-delay flag for this stream.

        By default, small messages may be delayed and/or combined to minimize
        the number of packets sent.  This can sometimes cause 200-500ms delays
        due to the interaction between Nagle's algorithm and TCP delayed
        ACKs.  To reduce this delay (at the expense of possibly increasing
        bandwidth usage), call ``self.set_nodelay(True)`` once the websocket
        connection is established.

        See `.BaseIOStream.set_nodelay` for additional details.

        .. versionadded:: 3.1
        """
        assert self.ws_connection is not None
        self.ws_connection.set_nodelay(value)

    def on_connection_close(self) -> None:
        if self.ws_connection:
            self.ws_connection.on_connection_close()
            self.ws_connection = None
        if not self._on_close_called:
            self._on_close_called = True
            self.on_close()
            self._break_cycles()

    def on_ws_connection_close(
        self, close_code: Optional[int] = None, close_reason: Optional[str] = None
    ) -> None:
        self.close_code = close_code
        self.close_reason = close_reason
        self.on_connection_close()

    def _break_cycles(self) -> None:
        # WebSocketHandlers call finish() early, but we don't want to
        # break up reference cycles (which makes it impossible to call
        # self.render_string) until after we've really closed the
        # connection (if it was established in the first place,
        # indicated by status code 101).
        if self.get_status() != 101 or self._on_close_called:
            super()._break_cycles()

    def send_error(self, *args: Any, **kwargs: Any) -> None:
        if self.stream is None:
            super().send_error(*args, **kwargs)
        else:
            # If we get an uncaught exception during the handshake,
            # we have no choice but to abruptly close the connection.
            # TODO: for uncaught exceptions after the handshake,
            # we can close the connection more gracefully.
            self.stream.close()

    def get_websocket_protocol(self) -> Optional["WebSocketProtocol"]:
        websocket_version = self.request.headers.get("Sec-WebSocket-Version")
        if websocket_version in ("7", "8", "13"):
            params = _WebSocketParams(
                ping_interval=self.ping_interval,
                ping_timeout=self.ping_timeout,
                max_message_size=self.max_message_size,
                compression_options=self.get_compression_options(),
            )
            return WebSocketProtocol13(self, False, params)
        return None

    def _detach_stream(self) -> IOStream:
        # disable non-WS methods
        for method in [
            "write",
            "redirect",
            "set_header",
            "set_cookie",
            "set_status",
            "flush",
            "finish",
        ]:
            setattr(self, method, _raise_not_supported_for_websockets)
        return self.detach()


def _raise_not_supported_for_websockets(*args: Any, **kwargs: Any) -> None:
    raise RuntimeError("Method not supported for Web Sockets")


class WebSocketProtocol(abc.ABC):
    """Base class for WebSocket protocol versions.
    """

    def __init__(self, handler: "_WebSocketDelegate") -> None:
        self.handler = handler
        self.stream = None  # type: Optional[IOStream]
        self.client_terminated = False
        self.server_terminated = False

    def _run_callback(
        self, callback: Callable, *args: Any, **kwargs: Any
    ) -> "Optional[Future[Any]]":
        """Runs the given callback with exception handling.

        If the callback is a coroutine, returns its Future. On error, aborts the
        websocket connection and returns None.
        """
        try:
            result = callback(*args, **kwargs)
        except Exception:
            self.handler.log_exception(*sys.exc_info())
            self._abort()
            return None
        else:
            if result is not None:
                result = gen.convert_yielded(result)
                assert self.stream is not None
                self.stream.io_loop.add_future(result, lambda f: f.result())
            return result

    def on_connection_close(self) -> None:
        self._abort()

    def _abort(self) -> None:
        """Instantly aborts the WebSocket connection by closing the socket"""
        self.client_terminated = True
        self.server_terminated = True
        if self.stream is not None:
            self.stream.close()  # forcibly tear down the connection
        self.close()  # let the subclass cleanup

    @abc.abstractmethod
    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def is_closing(self) -> bool:
        raise NotImplementedError()

    @abc.abstractmethod
    async def accept_connection(self, handler: WebSocketHandler) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        raise NotImplementedError()

    @property
    @abc.abstractmethod
    def selected_subprotocol(self) -> Optional[str]:
        raise NotImplementedError()

    @abc.abstractmethod
    def write_ping(self, data: bytes) -> None:
        raise NotImplementedError()

    # The entry points below are used by WebSocketClientConnection,
    # which was introduced after we only supported a single version of
    # WebSocketProtocol. The WebSocketProtocol/WebSocketProtocol13
    # boundary is currently pretty ad-hoc.
    @abc.abstractmethod
    def _process_server_headers(
        self, key: Union[str, bytes], headers: httputil.HTTPHeaders
    ) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def start_pinging(self) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    async def _receive_frame_loop(self) -> None:
        raise NotImplementedError()

    @abc.abstractmethod
    def set_nodelay(self, x: bool) -> None:
        raise NotImplementedError()


class _PerMessageDeflateCompressor(object):
    def __init__(
        self,
        persistent: bool,
        max_wbits: Optional[int],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        if max_wbits is None:
            max_wbits = zlib.MAX_WBITS
        # There is no symbolic constant for the minimum wbits value.
        if not (8 <= max_wbits <= zlib.MAX_WBITS):
            raise ValueError(
                "Invalid max_wbits value %r; allowed range 8-%d",
                max_wbits,
                zlib.MAX_WBITS,
            )
        self._max_wbits = max_wbits

        if (
            compression_options is None
            or "compression_level" not in compression_options
        ):
            self._compression_level = tornado.web.GZipContentEncoding.GZIP_LEVEL
        else:
            self._compression_level = compression_options["compression_level"]

        if compression_options is None or "mem_level" not in compression_options:
            self._mem_level = 8
        else:
            self._mem_level = compression_options["mem_level"]

        if persistent:
            self._compressor = self._create_compressor()  # type: Optional[_Compressor]
        else:
            self._compressor = None

    def _create_compressor(self) -> "_Compressor":
        return zlib.compressobj(
            self._compression_level, zlib.DEFLATED, -self._max_wbits, self._mem_level
        )

    def compress(self, data: bytes) -> bytes:
        compressor = self._compressor or self._create_compressor()
        data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)
        assert data.endswith(b"\x00\x00\xff\xff")
        return data[:-4]


class _PerMessageDeflateDecompressor(object):
    def __init__(
        self,
        persistent: bool,
        max_wbits: Optional[int],
        max_message_size: int,
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        self._max_message_size = max_message_size
        if max_wbits is None:
            max_wbits = zlib.MAX_WBITS
        if not (8 <= max_wbits <= zlib.MAX_WBITS):
            raise ValueError(
                "Invalid max_wbits value %r; allowed range 8-%d",
                max_wbits,
                zlib.MAX_WBITS,
            )
        self._max_wbits = max_wbits
        if persistent:
            self._decompressor = (
                self._create_decompressor()
            )  # type: Optional[_Decompressor]
        else:
            self._decompressor = None

    def _create_decompressor(self) -> "_Decompressor":
        return zlib.decompressobj(-self._max_wbits)

    def decompress(self, data: bytes) -> bytes:
        decompressor = self._decompressor or self._create_decompressor()
        result = decompressor.decompress(
            data + b"\x00\x00\xff\xff", self._max_message_size
        )
        if decompressor.unconsumed_tail:
            raise _DecompressTooLargeError()
        return result


class WebSocketProtocol13(WebSocketProtocol):
    """Implementation of the WebSocket protocol from RFC 6455.

    This class supports versions 7 and 8 of the protocol in addition to the
    final version 13.
    """

    # Bit masks for the first byte of a frame.
    FIN = 0x80
    RSV1 = 0x40
    RSV2 = 0x20
    RSV3 = 0x10
    RSV_MASK = RSV1 | RSV2 | RSV3
    OPCODE_MASK = 0x0F

    stream = None  # type: IOStream

    def __init__(
        self,
        handler: "_WebSocketDelegate",
        mask_outgoing: bool,
        params: _WebSocketParams,
    ) -> None:
        WebSocketProtocol.__init__(self, handler)
        self.mask_outgoing = mask_outgoing
        self.params = params
        self._final_frame = False
        self._frame_opcode = None
        self._masked_frame = None
        self._frame_mask = None  # type: Optional[bytes]
        self._frame_length = None
        self._fragmented_message_buffer = None  # type: Optional[bytes]
        self._fragmented_message_opcode = None
        self._waiting = None  # type: object
        self._compression_options = params.compression_options
        self._decompressor = None  # type: Optional[_PerMessageDeflateDecompressor]
        self._compressor = None  # type: Optional[_PerMessageDeflateCompressor]
        self._frame_compressed = None  # type: Optional[bool]
        # The total uncompressed size of all messages received or sent.
        # Unicode messages are encoded to utf8.
        # Only for testing; subject to change.
        self._message_bytes_in = 0
        self._message_bytes_out = 0
        # The total size of all packets received or sent.  Includes
        # the effect of compression, frame overhead, and control frames.
        self._wire_bytes_in = 0
        self._wire_bytes_out = 0
        self.ping_callback = None  # type: Optional[PeriodicCallback]
        self.last_ping = 0.0
        self.last_pong = 0.0
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]

    # Use a property for this to satisfy the abc.
    @property
    def selected_subprotocol(self) -> Optional[str]:
        return self._selected_subprotocol

    @selected_subprotocol.setter
    def selected_subprotocol(self, value: Optional[str]) -> None:
        self._selected_subprotocol = value

    async def accept_connection(self, handler: WebSocketHandler) -> None:
        try:
            self._handle_websocket_headers(handler)
        except ValueError:
            handler.set_status(400)
            log_msg = "Missing/Invalid WebSocket headers"
            handler.finish(log_msg)
            gen_log.debug(log_msg)
            return

        try:
            await self._accept_connection(handler)
        except asyncio.CancelledError:
            self._abort()
            return
        except ValueError:
            gen_log.debug("Malformed WebSocket request received", exc_info=True)
            self._abort()
            return

    def _handle_websocket_headers(self, handler: WebSocketHandler) -> None:
        """Verifies all invariant- and required headers

        If a header is missing or have an incorrect value ValueError will be
        raised
        """
        fields = ("Host", "Sec-Websocket-Key", "Sec-Websocket-Version")
        if not all(map(lambda f: handler.request.headers.get(f), fields)):
            raise ValueError("Missing/Invalid WebSocket headers")

    @staticmethod
    def compute_accept_value(key: Union[str, bytes]) -> str:
        """Computes the value for the Sec-WebSocket-Accept header,
        given the value for Sec-WebSocket-Key.
        """
        sha1 = hashlib.sha1()
        sha1.update(utf8(key))
        sha1.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")  # Magic value
        return native_str(base64.b64encode(sha1.digest()))

    def _challenge_response(self, handler: WebSocketHandler) -> str:
        return WebSocketProtocol13.compute_accept_value(
            cast(str, handler.request.headers.get("Sec-Websocket-Key"))
        )

    async def _accept_connection(self, handler: WebSocketHandler) -> None:
        subprotocol_header = handler.request.headers.get("Sec-WebSocket-Protocol")
        if subprotocol_header:
            subprotocols = [s.strip() for s in subprotocol_header.split(",")]
        else:
            subprotocols = []
        self.selected_subprotocol = handler.select_subprotocol(subprotocols)
        if self.selected_subprotocol:
            assert self.selected_subprotocol in subprotocols
            handler.set_header("Sec-WebSocket-Protocol", self.selected_subprotocol)

        extensions = self._parse_extensions_header(handler.request.headers)
        for ext in extensions:
            if ext[0] == "permessage-deflate" and self._compression_options is not None:
                # TODO: negotiate parameters if compression_options
                # specifies limits.
                self._create_compressors("server", ext[1], self._compression_options)
                if (
                    "client_max_window_bits" in ext[1]
                    and ext[1]["client_max_window_bits"] is None
                ):
                    # Don't echo an offered client_max_window_bits
                    # parameter with no value.
                    del ext[1]["client_max_window_bits"]
                handler.set_header(
                    "Sec-WebSocket-Extensions",
                    httputil._encode_header("permessage-deflate", ext[1]),
                )
                break

        handler.clear_header("Content-Type")
        handler.set_status(101)
        handler.set_header("Upgrade", "websocket")
        handler.set_header("Connection", "Upgrade")
        handler.set_header("Sec-WebSocket-Accept", self._challenge_response(handler))
        handler.finish()

        self.stream = handler._detach_stream()

        self.start_pinging()
        try:
            open_result = handler.open(*handler.open_args, **handler.open_kwargs)
            if open_result is not None:
                await open_result
        except Exception:
            handler.log_exception(*sys.exc_info())
            self._abort()
            return

        await self._receive_frame_loop()

    def _parse_extensions_header(
        self, headers: httputil.HTTPHeaders
    ) -> List[Tuple[str, Dict[str, str]]]:
        extensions = headers.get("Sec-WebSocket-Extensions", "")
        if extensions:
            return [httputil._parse_header(e.strip()) for e in extensions.split(",")]
        return []

    def _process_server_headers(
        self, key: Union[str, bytes], headers: httputil.HTTPHeaders
    ) -> None:
        """Process the headers sent by the server to this client connection.

        'key' is the websocket handshake challenge/response key.
        """
        assert headers["Upgrade"].lower() == "websocket"
        assert headers["Connection"].lower() == "upgrade"
        accept = self.compute_accept_value(key)
        assert headers["Sec-Websocket-Accept"] == accept

        extensions = self._parse_extensions_header(headers)
        for ext in extensions:
            if ext[0] == "permessage-deflate" and self._compression_options is not None:
                self._create_compressors("client", ext[1])
            else:
                raise ValueError("unsupported extension %r", ext)

        self.selected_subprotocol = headers.get("Sec-WebSocket-Protocol", None)

    def _get_compressor_options(
        self,
        side: str,
        agreed_parameters: Dict[str, Any],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Converts a websocket agreed_parameters set to keyword arguments
        for our compressor objects.
        """
        options = dict(
            persistent=(side + "_no_context_takeover") not in agreed_parameters
        )  # type: Dict[str, Any]
        wbits_header = agreed_parameters.get(side + "_max_window_bits", None)
        if wbits_header is None:
            options["max_wbits"] = zlib.MAX_WBITS
        else:
            options["max_wbits"] = int(wbits_header)
        options["compression_options"] = compression_options
        return options

    def _create_compressors(
        self,
        side: str,
        agreed_parameters: Dict[str, Any],
        compression_options: Optional[Dict[str, Any]] = None,
    ) -> None:
        # TODO: handle invalid parameters gracefully
        allowed_keys = set(
            [
                "server_no_context_takeover",
                "client_no_context_takeover",
                "server_max_window_bits",
                "client_max_window_bits",
            ]
        )
        for key in agreed_parameters:
            if key not in allowed_keys:
                raise ValueError("unsupported compression parameter %r" % key)
        other_side = "client" if (side == "server") else "server"
        self._compressor = _PerMessageDeflateCompressor(
            **self._get_compressor_options(side, agreed_parameters, compression_options)
        )
        self._decompressor = _PerMessageDeflateDecompressor(
            max_message_size=self.params.max_message_size,
            **self._get_compressor_options(
                other_side, agreed_parameters, compression_options
            )
        )

    def _write_frame(
        self, fin: bool, opcode: int, data: bytes, flags: int = 0
    ) -> "Future[None]":
        data_len = len(data)
        if opcode & 0x8:
            # All control frames MUST have a payload length of 125
            # bytes or less and MUST NOT be fragmented.
            if not fin:
                raise ValueError("control frames may not be fragmented")
            if data_len > 125:
                raise ValueError("control frame payloads may not exceed 125 bytes")
        if fin:
            finbit = self.FIN
        else:
            finbit = 0
        frame = struct.pack("B", finbit | opcode | flags)
        if self.mask_outgoing:
            mask_bit = 0x80
        else:
            mask_bit = 0
        if data_len < 126:
            frame += struct.pack("B", data_len | mask_bit)
        elif data_len <= 0xFFFF:
            frame += struct.pack("!BH", 126 | mask_bit, data_len)
        else:
            frame += struct.pack("!BQ", 127 | mask_bit, data_len)
        if self.mask_outgoing:
            mask = os.urandom(4)
            data = mask + _websocket_mask(mask, data)
        frame += data
        self._wire_bytes_out += len(frame)
        return self.stream.write(frame)

    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        """Sends the given message to the client of this Web Socket."""
        if binary:
            opcode = 0x2
        else:
            opcode = 0x1
        message = tornado.escape.utf8(message)
        assert isinstance(message, bytes)
        self._message_bytes_out += len(message)
        flags = 0
        if self._compressor:
            message = self._compressor.compress(message)
            flags |= self.RSV1
        # For historical reasons, write methods in Tornado operate in a semi-synchronous
        # mode in which awaiting the Future they return is optional (But errors can
        # still be raised). This requires us to go through an awkward dance here
        # to transform the errors that may be returned while presenting the same
        # semi-synchronous interface.
        try:
            fut = self._write_frame(True, opcode, message, flags=flags)
        except StreamClosedError:
            raise WebSocketClosedError()

        async def wrapper() -> None:
            try:
                await fut
            except StreamClosedError:
                raise WebSocketClosedError()

        return asyncio.ensure_future(wrapper())

    def write_ping(self, data: bytes) -> None:
        """Send ping frame."""
        assert isinstance(data, bytes)
        self._write_frame(True, 0x9, data)

    async def _receive_frame_loop(self) -> None:
        try:
            while not self.client_terminated:
                await self._receive_frame()
        except StreamClosedError:
            self._abort()
        self.handler.on_ws_connection_close(self.close_code, self.close_reason)

    async def _read_bytes(self, n: int) -> bytes:
        data = await self.stream.read_bytes(n)
        self._wire_bytes_in += n
        return data

    async def _receive_frame(self) -> None:
        # Read the frame header.
        data = await self._read_bytes(2)
        header, mask_payloadlen = struct.unpack("BB", data)
        is_final_frame = header & self.FIN
        reserved_bits = header & self.RSV_MASK
        opcode = header & self.OPCODE_MASK
        opcode_is_control = opcode & 0x8
        if self._decompressor is not None and opcode != 0:
            # Compression flag is present in the first frame's header,
            # but we can't decompress until we have all the frames of
            # the message.
            self._frame_compressed = bool(reserved_bits & self.RSV1)
            reserved_bits &= ~self.RSV1
        if reserved_bits:
            # client is using as-yet-undefined extensions; abort
            self._abort()
            return
        is_masked = bool(mask_payloadlen & 0x80)
        payloadlen = mask_payloadlen & 0x7F

        # Parse and validate the length.
        if opcode_is_control and payloadlen >= 126:
            # control frames must have payload < 126
            self._abort()
            return
        if payloadlen < 126:
            self._frame_length = payloadlen
        elif payloadlen == 126:
            data = await self._read_bytes(2)
            payloadlen = struct.unpack("!H", data)[0]
        elif payloadlen == 127:
            data = await self._read_bytes(8)
            payloadlen = struct.unpack("!Q", data)[0]
        new_len = payloadlen
        if self._fragmented_message_buffer is not None:
            new_len += len(self._fragmented_message_buffer)
        if new_len > self.params.max_message_size:
            self.close(1009, "message too big")
            self._abort()
            return

        # Read the payload, unmasking if necessary.
        if is_masked:
            self._frame_mask = await self._read_bytes(4)
        data = await self._read_bytes(payloadlen)
        if is_masked:
            assert self._frame_mask is not None
            data = _websocket_mask(self._frame_mask, data)

        # Decide what to do with this frame.
        if opcode_is_control:
            # control frames may be interleaved with a series of fragmented
            # data frames, so control frames must not interact with
            # self._fragmented_*
            if not is_final_frame:
                # control frames must not be fragmented
                self._abort()
                return
        elif opcode == 0:  # continuation frame
            if self._fragmented_message_buffer is None:
                # nothing to continue
                self._abort()
                return
            self._fragmented_message_buffer += data
            if is_final_frame:
                opcode = self._fragmented_message_opcode
                data = self._fragmented_message_buffer
                self._fragmented_message_buffer = None
        else:  # start of new data message
            if self._fragmented_message_buffer is not None:
                # can't start new message until the old one is finished
                self._abort()
                return
            if not is_final_frame:
                self._fragmented_message_opcode = opcode
                self._fragmented_message_buffer = data

        if is_final_frame:
            handled_future = self._handle_message(opcode, data)
            if handled_future is not None:
                await handled_future

    def _handle_message(self, opcode: int, data: bytes) -> "Optional[Future[None]]":
        """Execute on_message, returning its Future if it is a coroutine."""
        if self.client_terminated:
            return None

        if self._frame_compressed:
            assert self._decompressor is not None
            try:
                data = self._decompressor.decompress(data)
            except _DecompressTooLargeError:
                self.close(1009, "message too big after decompression")
                self._abort()
                return None

        if opcode == 0x1:
            # UTF-8 data
            self._message_bytes_in += len(data)
            try:
                decoded = data.decode("utf-8")
            except UnicodeDecodeError:
                self._abort()
                return None
            return self._run_callback(self.handler.on_message, decoded)
        elif opcode == 0x2:
            # Binary data
            self._message_bytes_in += len(data)
            return self._run_callback(self.handler.on_message, data)
        elif opcode == 0x8:
            # Close
            self.client_terminated = True
            if len(data) >= 2:
                self.close_code = struct.unpack(">H", data[:2])[0]
            if len(data) > 2:
                self.close_reason = to_unicode(data[2:])
            # Echo the received close code, if any (RFC 6455 section 5.5.1).
            self.close(self.close_code)
        elif opcode == 0x9:
            # Ping
            try:
                self._write_frame(True, 0xA, data)
            except StreamClosedError:
                self._abort()
            self._run_callback(self.handler.on_ping, data)
        elif opcode == 0xA:
            # Pong
            self.last_pong = IOLoop.current().time()
            return self._run_callback(self.handler.on_pong, data)
        else:
            self._abort()
        return None

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes the WebSocket connection."""
        if not self.server_terminated:
            if not self.stream.closed():
                if code is None and reason is not None:
                    code = 1000  # "normal closure" status code
                if code is None:
                    close_data = b""
                else:
                    close_data = struct.pack(">H", code)
                if reason is not None:
                    close_data += utf8(reason)
                try:
                    self._write_frame(True, 0x8, close_data)
                except StreamClosedError:
                    self._abort()
            self.server_terminated = True
        if self.client_terminated:
            if self._waiting is not None:
                self.stream.io_loop.remove_timeout(self._waiting)
                self._waiting = None
            self.stream.close()
        elif self._waiting is None:
            # Give the client a few seconds to complete a clean shutdown,
            # otherwise just close the connection.
            self._waiting = self.stream.io_loop.add_timeout(
                self.stream.io_loop.time() + 5, self._abort
            )
        if self.ping_callback:
            self.ping_callback.stop()
            self.ping_callback = None

    def is_closing(self) -> bool:
        """Return ``True`` if this connection is closing.

        The connection is considered closing if either side has
        initiated its closing handshake or if the stream has been
        shut down uncleanly.
        """
        return self.stream.closed() or self.client_terminated or self.server_terminated

    @property
    def ping_interval(self) -> Optional[float]:
        interval = self.params.ping_interval
        if interval is not None:
            return interval
        return 0

    @property
    def ping_timeout(self) -> Optional[float]:
        timeout = self.params.ping_timeout
        if timeout is not None:
            return timeout
        assert self.ping_interval is not None
        return max(3 * self.ping_interval, 30)

    def start_pinging(self) -> None:
        """Start sending periodic pings to keep the connection alive"""
        assert self.ping_interval is not None
        if self.ping_interval > 0:
            self.last_ping = self.last_pong = IOLoop.current().time()
            self.ping_callback = PeriodicCallback(
                self.periodic_ping, self.ping_interval * 1000
            )
            self.ping_callback.start()

    def periodic_ping(self) -> None:
        """Send a ping to keep the websocket alive

        Called periodically if the websocket_ping_interval is set and non-zero.
        """
        if self.is_closing() and self.ping_callback is not None:
            self.ping_callback.stop()
            return

        # Check for timeout on pong. Make sure that we really have
        # sent a recent ping in case the machine with both server and
        # client has been suspended since the last ping.
        now = IOLoop.current().time()
        since_last_pong = now - self.last_pong
        since_last_ping = now - self.last_ping
        assert self.ping_interval is not None
        assert self.ping_timeout is not None
        if (
            since_last_ping < 2 * self.ping_interval
            and since_last_pong > self.ping_timeout
        ):
            self.close()
            return

        self.write_ping(b"")
        self.last_ping = now

    def set_nodelay(self, x: bool) -> None:
        self.stream.set_nodelay(x)


class WebSocketClientConnection(simple_httpclient._HTTPConnection):
    """WebSocket client connection.

    This class should not be instantiated directly; use the
    `websocket_connect` function instead.
    """

    protocol = None  # type: WebSocketProtocol

    def __init__(
        self,
        request: httpclient.HTTPRequest,
        on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
        compression_options: Optional[Dict[str, Any]] = None,
        ping_interval: Optional[float] = None,
        ping_timeout: Optional[float] = None,
        max_message_size: int = _default_max_message_size,
        subprotocols: Optional[List[str]] = [],
    ) -> None:
        self.connect_future = Future()  # type: Future[WebSocketClientConnection]
        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]
        self.params = _WebSocketParams(
            ping_interval=ping_interval,
            ping_timeout=ping_timeout,
            max_message_size=max_message_size,
            compression_options=compression_options,
        )

        scheme, sep, rest = request.url.partition(":")
        scheme = {"ws": "http", "wss": "https"}[scheme]
        request.url = scheme + sep + rest
        request.headers.update(
            {
                "Upgrade": "websocket",
                "Connection": "Upgrade",
                "Sec-WebSocket-Key": self.key,
                "Sec-WebSocket-Version": "13",
            }
        )
        if subprotocols is not None:
            request.headers["Sec-WebSocket-Protocol"] = ",".join(subprotocols)
        if compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers[
                "Sec-WebSocket-Extensions"
            ] = "permessage-deflate; client_max_window_bits"

        self.tcp_client = TCPClient()
        super().__init__(
            None,
            request,
            lambda: None,
            self._on_http_response,
            104857600,
            self.tcp_client,
            65536,
            104857600,
        )

    def close(self, code: Optional[int] = None, reason: Optional[str] = None) -> None:
        """Closes the websocket connection.

        ``code`` and ``reason`` are documented under
        `WebSocketHandler.close`.

        .. versionadded:: 3.2

        .. versionchanged:: 4.0

           Added the ``code`` and ``reason`` arguments.
        """
        if self.protocol is not None:
            self.protocol.close(code, reason)
            self.protocol = None  # type: ignore

    def on_connection_close(self) -> None:
        if not self.connect_future.done():
            self.connect_future.set_exception(StreamClosedError())
        self._on_message(None)
        self.tcp_client.close()
        super().on_connection_close()

    def on_ws_connection_close(
        self, close_code: Optional[int] = None, close_reason: Optional[str] = None
    ) -> None:
        self.close_code = close_code
        self.close_reason = close_reason
        self.on_connection_close()

    def _on_http_response(self, response: httpclient.HTTPResponse) -> None:
        if not self.connect_future.done():
            if response.error:
                self.connect_future.set_exception(response.error)
            else:
                self.connect_future.set_exception(
                    WebSocketError("Non-websocket response")
                )

    async def headers_received(
        self,
        start_line: Union[httputil.RequestStartLine, httputil.ResponseStartLine],
        headers: httputil.HTTPHeaders,
    ) -> None:
        assert isinstance(start_line, httputil.ResponseStartLine)
        if start_line.code != 101:
            await super().headers_received(start_line, headers)
            return

        if self._timeout is not None:
            self.io_loop.remove_timeout(self._timeout)
            self._timeout = None

        self.headers = headers
        self.protocol = self.get_websocket_protocol()
        self.protocol._process_server_headers(self.key, self.headers)
        self.protocol.stream = self.connection.detach()

        IOLoop.current().add_callback(self.protocol._receive_frame_loop)
        self.protocol.start_pinging()

        # Once we've taken over the connection, clear the final callback
        # we set on the http request.  This deactivates the error handling
        # in simple_httpclient that would otherwise interfere with our
        # ability to see exceptions.
        self.final_callback = None  # type: ignore

        future_set_result_unless_cancelled(self.connect_future, self)

    def write_message(
        self, message: Union[str, bytes], binary: bool = False
    ) -> "Future[None]":
        """Sends a message to the WebSocket server.

        If the stream is closed, raises `WebSocketClosedError`.
        Returns a `.Future` which can be used for flow control.

        .. versionchanged:: 5.0
           Exception raised on a closed stream changed from `.StreamClosedError`
           to `WebSocketClosedError`.
        """
        return self.protocol.write_message(message, binary=binary)

    def read_message(
        self,
        callback: Optional[Callable[["Future[Union[None, str, bytes]]"], None]] = None,
    ) -> Awaitable[Union[None, str, bytes]]:
        """Reads a message from the WebSocket server.

        If on_message_callback was specified at WebSocket
        initialization, this function will never return messages

        Returns a future whose result is the message, or None
        if the connection is closed.  If a callback argument
        is given it will be called with the future when it is
        ready.
        """

        awaitable = self.read_queue.get()
        if callback is not None:
            self.io_loop.add_future(asyncio.ensure_future(awaitable), callback)
        return awaitable

    def on_message(self, message: Union[str, bytes]) -> Optional[Awaitable[None]]:
        return self._on_message(message)

    def _on_message(
        self, message: Union[None, str, bytes]
    ) -> Optional[Awaitable[None]]:
        if self._on_message_callback:
            self._on_message_callback(message)
            return None
        else:
            return self.read_queue.put(message)

    def ping(self, data: bytes = b"") -> None:
        """Send ping frame to the remote end.

        The data argument allows a small amount of data (up to 125
        bytes) to be sent as a part of the ping message. Note that not
        all websocket implementations expose this data to
        applications.

        Consider using the ``ping_interval`` argument to
        `websocket_connect` instead of sending pings manually.

        .. versionadded:: 5.1

        """
        data = utf8(data)
        if self.protocol is None:
            raise WebSocketClosedError()
        self.protocol.write_ping(data)

    def on_pong(self, data: bytes) -> None:
        pass

    def on_ping(self, data: bytes) -> None:
        pass

    def get_websocket_protocol(self) -> WebSocketProtocol:
        return WebSocketProtocol13(self, mask_outgoing=True, params=self.params)

    @property
    def selected_subprotocol(self) -> Optional[str]:
        """The subprotocol selected by the server.

        .. versionadded:: 5.1
        """
        return self.protocol.selected_subprotocol

    def log_exception(
        self,
        typ: "Optional[Type[BaseException]]",
        value: Optional[BaseException],
        tb: Optional[TracebackType],
    ) -> None:
        assert typ is not None
        assert value is not None
        app_log.error("Uncaught exception %s", value, exc_info=(typ, value, tb))


def websocket_connect(
    url: Union[str, httpclient.HTTPRequest],
    callback: Optional[Callable[["Future[WebSocketClientConnection]"], None]] = None,
    connect_timeout: Optional[float] = None,
    on_message_callback: Optional[Callable[[Union[None, str, bytes]], None]] = None,
    compression_options: Optional[Dict[str, Any]] = None,
    ping_interval: Optional[float] = None,
    ping_timeout: Optional[float] = None,
    max_message_size: int = _default_max_message_size,
    subprotocols: Optional[List[str]] = None,
) -> "Awaitable[WebSocketClientConnection]":
    """Client-side websocket support.

    Takes a url and returns a Future whose result is a
    `WebSocketClientConnection`.

    ``compression_options`` is interpreted in the same way as the
    return value of `.WebSocketHandler.get_compression_options`.

    The connection supports two styles of operation. In the coroutine
    style, the application typically calls
    `~.WebSocketClientConnection.read_message` in a loop::

        conn = yield websocket_connect(url)
        while True:
            msg = yield conn.read_message()
            if msg is None: break
            # Do something with msg

    In the callback style, pass an ``on_message_callback`` to
    ``websocket_connect``. In both styles, a message of ``None``
    indicates that the connection has been closed.

    ``subprotocols`` may be a list of strings specifying proposed
    subprotocols. The selected protocol may be found on the
    ``selected_subprotocol`` attribute of the connection object
    when the connection is complete.

    .. versionchanged:: 3.2
       Also accepts ``HTTPRequest`` objects in place of urls.

    .. versionchanged:: 4.1
       Added ``compression_options`` and ``on_message_callback``.

    .. versionchanged:: 4.5
       Added the ``ping_interval``, ``ping_timeout``, and ``max_message_size``
       arguments, which have the same meaning as in `WebSocketHandler`.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.1
       Added the ``subprotocols`` argument.
    """
    if isinstance(url, httpclient.HTTPRequest):
        assert connect_timeout is None
        request = url
        # Copy and convert the headers dict/object (see comments in
        # AsyncHTTPClient.fetch)
        request.headers = httputil.HTTPHeaders(request.headers)
    else:
        request = httpclient.HTTPRequest(url, connect_timeout=connect_timeout)
    request = cast(
        httpclient.HTTPRequest,
        httpclient._RequestProxy(request, httpclient.HTTPRequest._DEFAULTS),
    )
    conn = WebSocketClientConnection(
        request,
        on_message_callback=on_message_callback,
        compression_options=compression_options,
        ping_interval=ping_interval,
        ping_timeout=ping_timeout,
        max_message_size=max_message_size,
        subprotocols=subprotocols,
    )
    if callback is not None:
        IOLoop.current().add_future(conn.connect_future, callback)
    return conn.connect_future

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user