Skip to content

Commit

Permalink
Add a distinct exception for writing a WebSocket message on a closed …
Browse files Browse the repository at this point in the history
…connection.

This replaces an AttributeError on NoneType.

Closes tornadoweb#879.
  • Loading branch information
bdarnell committed Aug 18, 2013
1 parent fdbebac commit 6ec711c
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions tornado/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ class WebSocketError(Exception):
pass


class WebSocketClosedError(WebSocketError):
pass


class WebSocketHandler(tornado.web.RequestHandler):
"""Subclass this class to create a basic WebSocket handler.
Expand Down Expand Up @@ -160,6 +164,8 @@ def write_message(self, message, binary=False):
message will be sent as utf8; in binary mode any byte string
is allowed.
"""
if self.ws_connection is None:
raise WebSocketClosedError()
if isinstance(message, dict):
message = tornado.escape.json_encode(message)
self.ws_connection.write_message(message, binary=binary)
Expand Down Expand Up @@ -195,6 +201,8 @@ def on_message(self, message):

def ping(self, data):
"""Send ping frame to the remote end."""
if self.ws_connection is None:
raise WebSocketClosedError()
self.ws_connection.write_ping(data)

def on_pong(self, data):
Expand All @@ -210,8 +218,9 @@ def close(self):
Once the close handshake is successful the socket will be closed.
"""
self.ws_connection.close()
self.ws_connection = None
if self.ws_connection:
self.ws_connection.close()
self.ws_connection = None

def allow_draft76(self):
"""Override to enable support for the older "draft76" protocol.
Expand Down

0 comments on commit 6ec711c

Please sign in to comment.