本文整理汇总了Python中tornado.websocket方法的典型用法代码示例。如果您正苦于以下问题:Python tornado.websocket方法的具体用法?Python tornado.websocket怎么用?Python tornado.websocket使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado
的用法示例。
在下文中一共展示了tornado.websocket方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _execute
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例2: test_app_auth_with_valid_pubkey_by_multipart_form
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例3: test_app_for_sending_message_with_large_size
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例4: on_read
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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')
示例5: initialize_websocket_server
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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
示例6: _execute
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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)
示例7: open
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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?
示例8: check_origin
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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
示例9: test_app_auth_with_valid_pubkey_by_urlencoded_form
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例10: test_app_auth_with_valid_pubkey_by_multipart_form
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例11: _gc
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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
示例12: main
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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)
示例13: start_server
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例14: on_read
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
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()
示例15: open
# 需要导入模块: import tornado [as 别名]
# 或者: from tornado import websocket [as 别名]
def open(self):
logging.debug('websocket open')
self.application.register_client(self)