🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### Navigation - [index](# "General Index") - [modules](# "Python Module Index") | - [next](# "HTTP servers and clients") | - [previous](# "tornado.locale — Internationalization support") | - [Tornado 4.4.dev1 documentation](#) » - [Web framework](#) » # `tornado.websocket` — Bidirectional communication to the browser Implementation of the WebSocket protocol. [WebSockets](http://dev.w3.org/html5/websockets/) [http://dev.w3.org/html5/websockets/] allow for bidirectionalcommunication 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](http://caniuse.com/websockets) for details). This module implements the final version of the WebSocket protocol asdefined in [RFC 6455](http://tools.ietf.org/html/rfc6455) [http://tools.ietf.org/html/rfc6455]. Certainbrowser versions (notably Safari 5.x) implemented an earlier draft ofthe protocol (known as “draft 76”) and are not compatible with this module. Changed in version 4.0: Removed support for the draft 76 protocol version. *class *`tornado.websocket.``WebSocketHandler`(*application*, *request*, ***kwargs*)[[source]](#) Subclass this class to create a basic WebSocket handler. Override [`on_message`](# "tornado.websocket.WebSocketHandler.on_message") to handle incoming messages, and use[`write_message`](# "tornado.websocket.WebSocketHandler.write_message") to send messages to the client. You can alsooverride [`open`](# "tornado.websocket.WebSocketHandler.open") and [`on_close`](# "tornado.websocket.WebSocketHandler.on_close") to handle opened and closedconnections. See [http://dev.w3.org/html5/websockets/](http://dev.w3.org/html5/websockets/) for details on theJavaScript interface. The protocol is specified at[http://tools.ietf.org/html/rfc6455](http://tools.ietf.org/html/rfc6455). Here is an example WebSocket handler that echos back all received messagesback to the client: ~~~ 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") ~~~ WebSockets are not standard HTTP connections. The “handshake” isHTTP, but after the handshake, the protocol ismessage-based. Consequently, most of the Tornado HTTP facilitiesare not available in handlers of this type. The only communicationmethods available to you are [`write_message()`](# "tornado.websocket.WebSocketHandler.write_message"), [`ping()`](# "tornado.websocket.WebSocketHandler.ping"), and[`close()`](# "tornado.websocket.WebSocketHandler.close"). Likewise, your request handler class should implement[`open()`](# "tornado.websocket.WebSocketHandler.open") method rather than `get()` or `post()`. If you map the handler above to `/websocket` in your application, you caninvoke 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 networkaccess from javascript. This can be surprising and is a potentialsecurity hole, so since Tornado 4.0 [`WebSocketHandler`](# "tornado.websocket.WebSocketHandler") requiresapplications that wish to receive cross-origin websockets to opt inby overriding the [`check_origin`](# "tornado.websocket.WebSocketHandler.check_origin") method (see thatmethod's docs for details). Failure to do so is the most likelycause of 403 errors when making a websocket connection. When using a secure websocket connection (`wss://`) with a self-signedcertificate, the connection from a browser may fail because it wantsto show the “accept this certificate” dialog but has nowhere to show it.You must first visit a regular HTML page using the same certificateto accept it before the websocket connection will succeed. ### Event handlers `WebSocketHandler.``open`(**args*, ***kwargs*)[[source]](#) Invoked when a new WebSocket is opened. The arguments to [`open`](# "tornado.websocket.WebSocketHandler.open") are extracted from the [`tornado.web.URLSpec`](# "tornado.web.URLSpec")regular expression, just like the arguments to[`tornado.web.RequestHandler.get`](# "tornado.web.RequestHandler.get"). `WebSocketHandler.``on_message`(*message*)[[source]](#) Handle incoming messages on the WebSocket This method must be overridden. `WebSocketHandler.``on_close`()[[source]](#) Invoked when the WebSocket is closed. If the connection was closed cleanly and a status code or reasonphrase was supplied, these values will be available as the attributes`self.close_code` and `self.close_reason`. Changed in version 4.0: Added `close_code` and `close_reason` attributes. `WebSocketHandler.``select_subprotocol`(*subprotocols*)[[source]](#) Invoked when a new WebSocket requests specific subprotocols. `subprotocols` is a list of strings identifying thesubprotocols proposed by the client. This method may beoverridden to return one of those strings to select it, or`None` to not select a subprotocol. Failure to select asubprotocol does not automatically abort the connection,although clients may close the connection if none of theirproposed subprotocols was selected. ### Output `WebSocketHandler.``write_message`(*message*, *binary=False*)[[source]](#) Sends the given message to the client of this Web Socket. The message may be either a string or a dict (which will beencoded as json). If the `binary` argument is false, themessage will be sent as utf8; in binary mode any byte stringis allowed. If the connection is already closed, raises [`WebSocketClosedError`](# "tornado.websocket.WebSocketClosedError"). Changed in version 3.2: [`WebSocketClosedError`](# "tornado.websocket.WebSocketClosedError") was added (previously a closed connectionwould raise an [`AttributeError`](https://docs.python.org/3.4/library/exceptions.html#AttributeError "(in Python v3.4)") [https://docs.python.org/3.4/library/exceptions.html#AttributeError]) Changed in version 4.3: Returns a [`Future`](# "tornado.concurrent.Future") which can be used for flow control. `WebSocketHandler.``close`(*code=None*, *reason=None*)[[source]](#) 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 valuesdefined in [RFC 6455 section 7.4.1](https://tools.ietf.org/html/rfc6455#section-7.4.1) [https://tools.ietf.org/html/rfc6455#section-7.4.1].`reason` may be a textual message about why the connection isclosing. These values are made available to the client, but arenot otherwise interpreted by the websocket protocol. Changed in version 4.0: Added the `code` and `reason` arguments. ### Configuration `WebSocketHandler.``check_origin`(*origin*)[[source]](#) Override to enable support for allowing alternate origins. The `origin` argument is the value of the `Origin` HTTPheader, the url responsible for initiating this request. Thismethod is not called for clients that do not send this header;such requests are always allowed (because all browsers thatimplement WebSockets support this header, and non-browserclients 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 otherthan this one. This is a security protection against cross site scripting attacks onbrowsers, since WebSockets are allowed to bypass the usual same-originpolicies and don't use CORS headers. To accept all cross-origin traffic (which was the default prior toTornado 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 mightdo something like: ~~~ def check_origin(self, origin): parsed_origin = urllib.parse.urlparse(origin) return parsed_origin.netloc.endswith(".mydomain.com") ~~~ New in version 4.0. `WebSocketHandler.``get_compression_options`()[[source]](#) Override to return compression options for the connection. If this method returns None (the default), compression willbe disabled. If it returns a dict (even an empty one), itwill be enabled. The contents of the dict may be used tocontrol the memory and CPU usage of the compression,but no such options are currently implemented. New in version 4.1. `WebSocketHandler.``set_nodelay`(*value*)[[source]](#) Set the no-delay flag for this stream. By default, small messages may be delayed and/or combined to minimizethe number of packets sent. This can sometimes cause 200-500ms delaysdue to the interaction between Nagle's algorithm and TCP delayedACKs. To reduce this delay (at the expense of possibly increasingbandwidth usage), call `self.set_nodelay(True)` once the websocketconnection is established. See [`BaseIOStream.set_nodelay`](# "tornado.iostream.BaseIOStream.set_nodelay") for additional details. New in version 3.1. ### Other `WebSocketHandler.``ping`(*data*)[[source]](#) Send ping frame to the remote end. `WebSocketHandler.``on_pong`(*data*)[[source]](#) Invoked when the response to a ping frame is received. *exception *`tornado.websocket.``WebSocketClosedError`[[source]](#) Raised by operations on a closed connection. New in version 3.2. ### Client-side support `tornado.websocket.``websocket_connect`(*url*, *io_loop=None*, *callback=None*, *connect_timeout=None*, *on_message_callback=None*, *compression_options=None*)[[source]](#) Client-side websocket support. Takes a url and returns a Future whose result is a[`WebSocketClientConnection`](# "tornado.websocket.WebSocketClientConnection"). `compression_options` is interpreted in the same way as thereturn value of [`WebSocketHandler.get_compression_options`](# "tornado.websocket.WebSocketHandler.get_compression_options"). The connection supports two styles of operation. In the coroutinestyle, the application typically calls[`read_message`](# "tornado.websocket.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. Changed in version 3.2: Also accepts `HTTPRequest` objects in place of urls. Changed in version 4.1: Added `compression_options` and `on_message_callback`.The `io_loop` argument is deprecated. *class *`tornado.websocket.``WebSocketClientConnection`(*io_loop*, *request*, *on_message_callback=None*, *compression_options=None*)[[source]](#) WebSocket client connection. This class should not be instantiated directly; use the[`websocket_connect`](# "tornado.websocket.websocket_connect") function instead. `close`(*code=None*, *reason=None*)[[source]](#) Closes the websocket connection. `code` and `reason` are documented under[`WebSocketHandler.close`](# "tornado.websocket.WebSocketHandler.close"). New in version 3.2. Changed in version 4.0: Added the `code` and `reason` arguments. `write_message`(*message*, *binary=False*)[[source]](#) Sends a message to the WebSocket server. `read_message`(*callback=None*)[[source]](#) Reads a message from the WebSocket server. If on_message_callback was specified at WebSocketinitialization, this function will never return messages Returns a future whose result is the message, or Noneif the connection is closed. If a callback argumentis given it will be called with the future when it isready. © Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.