'Closes the WebSocket connection.'

def close(self, code=None, reason=None):

    if (not self.server_terminated):
        if (not self.stream.closed()):
            if ((code is None) and (reason is not None)):
                code = 1000
            if (code is None):
                close_data = ''
            else:
                close_data = struct.pack('>H', code)
            if (reason is not None):
                close_data += utf8(reason)
            self._write_frame(True, 8, close_data)
        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):
        self._waiting = self.stream.io_loop.add_timeout((self.stream.io_loop.time() + 5), self._abort)
