Python tornado.websocket() Examples

The following are 30 code examples of tornado.websocket(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado , or try the search function .
Example #1
Source File: handlers.py    From Computable with MIT License 7 votes vote down vote up
def _execute(self, transforms, *args, **kwargs):
        from tornado.websocket import WebSocketProtocol8, WebSocketProtocol76
        
        self.open_args = args
        self.open_kwargs = kwargs

        # 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 self.request.headers.get("Sec-WebSocket-Version") in ("7", "8", "13"):
            self.ws_connection = WebSocketProtocol8(self)
            self.ws_connection.accept_connection()
            
        elif self.request.headers.get("Sec-WebSocket-Version"):
            self.stream.write(tornado.escape.utf8(
                "HTTP/1.1 426 Upgrade Required\r\n"
                "Sec-WebSocket-Version: 8\r\n\r\n"))
            self.stream.close()
            
        else:
            self.ws_connection = WebSocketProtocol76(self)
            self.ws_connection.accept_connection() 
Example #2
Source File: test_app.py    From webssh with MIT License 7 votes vote down vote up
def test_app_for_sending_message_with_large_size(self):
        url = self.get_url('/')
        response = yield self.async_post(url, dict(self.body, username='foo'))
        data = json.loads(to_str(response.body))
        self.assert_status_none(data)

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)

        send = 'h' * (64 * 1024) + '\r\n\r\n'
        yield ws.write_message(json.dumps({'data': send}))
        lst = []
        while True:
            msg = yield ws.read_message()
            lst.append(msg)
            if msg.endswith(b'\r\n\r\n'):
                break
        recv = b''.join(lst).decode(data['encoding'])
        self.assertEqual(send, recv)
        ws.close() 
Example #3
Source File: main.py    From autoops with Apache License 2.0 6 votes vote down vote up
def on_read(self):
        logging.debug('worker {} on read'.format(self.id))
        try:
            data = self.chan.recv(BUF_SIZE)
        except (OSError, IOError) as e:
            logging.error(e)
            if errno_from_exception(e) in _ERRNO_CONNRESET:
                self.close()
        else:
            logging.debug('"{}" from {}'.format(data, self.dst_addr))
            if not data:
                self.close()
                return

            logging.debug('"{}" to {}'.format(data, self.handler.src_addr))
            try:
                self.handler.write_message(data)
            except tornado.websocket.WebSocketClosedError:
                self.close() 
Example #4
Source File: ipc.py    From cachebrowser with MIT License 6 votes vote down vote up
def initialize_websocket_server(self, port):
        app = tornado.web.Application([
            (r'/', WebSocketIPCClient, {'router': self.router}),
        ])

        def run_loop():
            logger.debug("Starting IPC websocket server on port {}".format(port))
            ioloop = tornado.ioloop.IOLoop()
            ioloop.make_current()
            app.listen(port)
            ioloop.start()

        t = Thread(target=run_loop)
        t.daemon = True
        t.start()

        return app 
Example #5
Source File: AttackMapServer.py    From geoip-attack-map with Apache License 2.0 6 votes vote down vote up
def main():
    # Register handler pages
    handlers = [
                (r'/websocket', WebSocketChatHandler),
                (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
                (r'/flags/(.*)', tornado.web.StaticFileHandler, {'path': 'static/flags'}),
                (r'/', IndexHandler)
                ]
    
    # Define the static path
    #static_path = path.join( path.dirname(__file__), 'static' )

    # Define static settings
    settings = {
                #'static_path': static_path
                }

    # Create and start app listening on port 8888
    try:
        app = tornado.web.Application(handlers, **settings)
        app.listen(8888)
        print('[*] Waiting on browser connections...')
        tornado.ioloop.IOLoop.instance().start()
    except Exception as appFail:
        print(appFail) 
Example #6
Source File: worker.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def on_read(self):
        logging.debug('worker {} on read'.format(self.id))
        try:
            data = self.chan.recv(BUF_SIZE)
        except (OSError, IOError) as e:
            logging.error(e)
            if errno_from_exception(e) in _ERRNO_CONNRESET:
                self.close(reason='chan error on reading')
        else:
            logging.debug('{!r} from {}:{}'.format(data, *self.dst_addr))
            if not data:
                self.close(reason='chan closed')
                return

            logging.debug('{!r} to {}:{}'.format(data, *self.handler.src_addr))
            try:
                self.handler.write_message(data, binary=True)
            except tornado.websocket.WebSocketClosedError:
                self.close(reason='websocket closed') 
Example #7
Source File: __init__.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def _gc(self):
        """Remove disconnected websocket handlers."""
        for directory in list(six.viewkeys(self.handlers)):
            handlers = [
                (pattern, handler, impl, sub_id)
                for pattern, handler, impl, sub_id in self.handlers[directory]
                if handler.active(sub_id=sub_id)
            ]

            _LOGGER.debug('Number of active handlers for %s: %s',
                          directory, len(handlers))

            if not handlers:
                _LOGGER.debug('No active handlers for %s', directory)
                self.handlers.pop(directory, None)
                if directory not in self.watch_dirs:
                    # Watch is not permanent, remove dir from watcher.
                    self.watcher.remove_dir(directory)
            else:
                self.handlers[directory] = handlers 
Example #8
Source File: _tornadoserver.py    From flexx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def open(self, path=None):
        """ Called when a new connection is made.
        """
        if not hasattr(self, 'close_code'):  # old version of Tornado?
            self.close_code, self.close_reason = None, None

        self._session = None
        self._mps_counter = MessageCounter()

        # Don't collect messages to send them more efficiently, just send asap
        # self.set_nodelay(True)

        if isinstance(path, bytes):
            path = path.decode()
        self.app_name = path.strip('/')

        logger.debug('New websocket connection %s' % path)
        if manager.has_app_name(self.app_name):
            self.application._io_loop.spawn_callback(self.pinger1)
        else:
            self.close(1003, "Could not associate socket with an app.")

    # todo: @gen.coroutine? 
Example #9
Source File: wssd.py    From deepin-remote-assistance with GNU General Public License v3.0 6 votes vote down vote up
def start_server(self):
        for port in range(PORT_MIN, PORT_MAX):
            try:
                self.application.listen(port)
                break
            # That port is unavailable
            except OSError:
                pass
        else:
            server_log.warn('[wssd] failed to start websocket server')
            # TODO: raise exception
            return

        self.port = port
        self.loop = tornado.ioloop.IOLoop.instance()
        self.loop.start() 
Example #10
Source File: worker.py    From webssh with MIT License 6 votes vote down vote up
def on_read(self):
        logging.debug('worker {} on read'.format(self.id))
        try:
            data = self.chan.recv(BUF_SIZE)
        except (OSError, IOError) as e:
            logging.error(e)
            if errno_from_exception(e) in _ERRNO_CONNRESET:
                self.close(reason='chan error on reading')
        else:
            logging.debug('{!r} from {}:{}'.format(data, *self.dst_addr))
            if not data:
                self.close(reason='chan closed')
                return

            logging.debug('{!r} to {}:{}'.format(data, *self.handler.src_addr))
            try:
                self.handler.write_message(data, binary=True)
            except tornado.websocket.WebSocketClosedError:
                self.close(reason='websocket closed') 
Example #11
Source File: test_app.py    From webssh with MIT License 6 votes vote down vote up
def test_app_auth_with_valid_pubkey_by_multipart_form(self):
        url = self.get_url('/')
        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        files = [('privatekey', 'user_rsa_key', privatekey)]
        content_type, body = encode_multipart_formdata(self.body_dict.items(),
                                                       files)
        headers = {
            'Content-Type': content_type, 'content-length': str(len(body))
        }
        response = yield self.async_post(url, body, headers=headers)
        data = json.loads(to_str(response.body))
        self.assert_status_none(data)

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close() 
Example #12
Source File: test_app.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def test_app_auth_with_valid_pubkey_by_multipart_form(self):
        url = self.get_url('/')
        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        files = [('privatekey', 'user_rsa_key', privatekey)]
        content_type, body = encode_multipart_formdata(self.body_dict.items(),
                                                       files)
        headers = {
            'Content-Type': content_type, 'content-length': str(len(body))
        }
        response = yield self.async_post(url, body, headers=headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close() 
Example #13
Source File: _tornadoserver.py    From flexx with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def check_origin(self, origin):
        """ Handle cross-domain access; override default same origin policy.
        """
        # http://www.tornadoweb.org/en/stable/_modules/tornado/websocket.html
        #WebSocketHandler.check_origin

        serving_host = self.request.headers.get("Host")
        serving_hostname, _, serving_port = serving_host.partition(':')
        connecting_host = urlparse(origin).netloc
        connecting_hostname, _, connecting_port = connecting_host.partition(':')

        serving_port = serving_port or '80'
        connecting_port = connecting_port or '80'

        if serving_hostname == 'localhost':
            return True  # Safe
        elif serving_host == connecting_host:
            return True  # Passed most strict test, hooray!
        elif serving_hostname == '0.0.0.0' and serving_port == connecting_port:
            return True  # host on all addressses; best we can do is check port
        elif connecting_host in config.host_whitelist:
            return True
        else:
            logger.warning('Connection refused from %s' % origin)
            return False 
Example #14
Source File: test_app.py    From adminset with GNU General Public License v2.0 6 votes vote down vote up
def test_app_auth_with_valid_pubkey_by_urlencoded_form(self):
        url = self.get_url('/')
        privatekey = read_file(make_tests_data_path('user_rsa_key'))
        self.body_dict.update(privatekey=privatekey)
        body = urlencode(self.body_dict)
        response = yield self.async_post(url, body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close() 
Example #15
Source File: pywebproxy.py    From MobileSF with GNU General Public License v3.0 6 votes vote down vote up
def _execute(self, transforms, *args, **kwargs):
        """
        Overriding of a method of WebSocketHandler
        """
        def start_tunnel(future):
            """
            A callback which is called when connection to url is successful
            """
            self.upstream = future.result() # We need upstream to write further messages
            self.handshake_request = self.upstream_connection.request # HTTPRequest needed for caching :P
            self.handshake_request.response_buffer = "" # Needed for websocket data & compliance with cache_handler stuff
            self.handshake_request.version = "HTTP/1.1" # Tiny hack to protect caching (But according to websocket standards)
            self.handshake_request.body = self.handshake_request.body or "" # I dont know why a None is coming :P
            tornado.websocket.WebSocketHandler._execute(self, transforms, *args, **kwargs) # The regular procedures are to be done

        # We try to connect to provided URL & then we proceed with connection on client side.
        self.upstream = self.upstream_connect(callback=start_tunnel) 
Example #16
Source File: handlers.py    From jupyter-server-proxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_close(self):
        """
        Called when the client closes our websocket connection.

        We close our connection to the backend too.
        """
        if hasattr(self, 'ws'):
            self.ws.close() 
Example #17
Source File: main.py    From autoops with Apache License 2.0 5 votes vote down vote up
def on_close(self):#websocket关闭
        logging.info('Disconnected from {}'.format(self.src_addr))
        worker = self.worker_ref() if self.worker_ref else None
        if worker:
            worker.close() 
Example #18
Source File: meta.py    From databench with MIT License 5 votes vote down vote up
def emit(self, signal, message='__nomessagetoken__'):
        data = {'signal': signal}
        if message != '__nomessagetoken__':
            data['load'] = message

        try:
            return self.write_message(
                json.dumps(data, default=json_encoder_default).encode('utf-8'))
        except tornado.websocket.WebSocketClosedError:
            pass 
Example #19
Source File: main.py    From autoops with Apache License 2.0 5 votes vote down vote up
def on_message(self, message):  #表示接到浏览器通过websocket传输的字符,这里一次一个字符。
        logging.debug('"{}" from {}'.format(message, self.src_addr))
        worker = self.worker_ref()
        worker.data_to_dst.append(message)
        worker.on_write() 
Example #20
Source File: websocket.py    From tornadis with MIT License 5 votes vote down vote up
def get(self):
        self.render("websocket.html") 
Example #21
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_correct_credentials_timeout(self):
        url = self.get_url('/')
        response = yield self.async_post(url, self.body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        yield tornado.gen.sleep(handler.DELAY + 0.1)
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertIsNone(msg)
        self.assertEqual(ws.close_reason, 'Websocket authentication failed.') 
Example #22
Source File: handlers.py    From jupyter-server-proxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_ping(self, data):
        """
        Called when the client pings our websocket connection.

        We proxy it to the backend.
        """
        self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data))
        self._record_activity()
        if hasattr(self, 'ws'):
            self.ws.protocol.write_ping(data) 
Example #23
Source File: handlers.py    From jupyter-server-proxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def http_get(self, host, port, proxy_path=''):
        '''Our non-websocket GET.'''
        raise NotImplementedError('Subclasses of ProxyHandler should implement http_get') 
Example #24
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_too_many_connections(self):
        url = self.get_url('/')
        client = self.get_http_client()
        body = urlencode(dict(self.body, username='foo'))
        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        worker_id = data['id']
        self.assertIsNotNone(worker_id)
        self.assertIsNotNone(data['encoding'])
        self.assertIsNone(data['status'])

        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['id'])
        self.assertIsNone(data['encoding'])
        self.assertEqual(data['status'], 'Too many connections.')

        ws_url = url.replace('http', 'ws') + 'ws?id=' + worker_id
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertIsNotNone(msg)

        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['id'])
        self.assertIsNone(data['encoding'])
        self.assertEqual(data['status'], 'Too many connections.')

        ws.close() 
Example #25
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_for_sending_message_with_large_size(self):
        url = self.get_url('/')
        client = self.get_http_client()
        body = urlencode(dict(self.body, username='foo'))
        response = yield client.fetch(url, method='POST', body=body,
                                      headers=self.headers)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)

        send = 'h' * (64 * 1024) + '\r\n\r\n'
        yield ws.write_message(json.dumps({'data': send}))
        lst = []
        while True:
            msg = yield ws.read_message()
            lst.append(msg)
            if msg.endswith(b'\r\n\r\n'):
                break
        recv = b''.join(lst).decode(data['encoding'])
        self.assertEqual(send, recv)
        ws.close() 
Example #26
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_correct_credentials_but_wrong_id(self):
        url = self.get_url('/')
        response = yield self.async_post(url, self.body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=1' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertIsNone(msg)
        self.assertIn('Websocket authentication failed', ws.close_reason) 
Example #27
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_correct_credentials_but_empty_id(self):
        url = self.get_url('/')
        response = yield self.async_post(url, self.body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id='
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertIsNone(msg)
        self.assertIn('Missing value id', ws.close_reason) 
Example #28
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_correct_credentials_but_without_id_argument(self):
        url = self.get_url('/')
        response = yield self.async_post(url, self.body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws'
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertIsNone(msg)
        self.assertIn('Missing argument id', ws.close_reason) 
Example #29
Source File: test_app.py    From adminset with GNU General Public License v2.0 5 votes vote down vote up
def test_app_with_correct_credentials_user_robey(self):
        url = self.get_url('/')
        response = yield self.async_post(url, self.body)
        data = json.loads(to_str(response.body))
        self.assertIsNone(data['status'])
        self.assertIsNotNone(data['id'])
        self.assertIsNotNone(data['encoding'])

        url = url.replace('http', 'ws')
        ws_url = url + 'ws?id=' + data['id']
        ws = yield tornado.websocket.websocket_connect(ws_url)
        msg = yield ws.read_message()
        self.assertEqual(to_str(msg, data['encoding']), banner)
        ws.close() 
Example #30
Source File: handlers.py    From doufen with MIT License 5 votes vote down vote up
def on_close(self):
        logging.debug('websocket close')
        self.application.unregister_client(self)