本文整理汇总了Python中ws4py.websocket.WebSocket类的典型用法代码示例。如果您正苦于以下问题:Python WebSocket类的具体用法?Python WebSocket怎么用?Python WebSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了WebSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_send_message_without_masking
def test_send_message_without_masking(self):
tm = TextMessage(b'hello world')
m = MagicMock()
ws = WebSocket(sock=m)
ws.send(tm)
m.sendall.assert_called_once_with(tm.single())
示例2: __init__
def __init__(self, *args, **kw):
"""
Constructor. This will be called automatically
by the server upon connection
"""
WebSocket.__init__(self, *args, **kw)
self.close_callback = None
示例3: test_sending_ping
def test_sending_ping(self):
tm = PingControlMessage("hello").single(mask=False)
m = MagicMock()
ws = WebSocket(sock=m)
ws.ping("hello")
m.sendall.assert_called_once_with(tm)
示例4: __init__
def __init__(self, *args, **kw):
WebSocket.__init__(self, *args, **kw)
print str(self) + "connected"
SUBSCRIBERS.add(self)
global NextUID
NextUID = NextUID + 1
UID = NextUID
示例5: __init__
def __init__(self, url, protocols, extensions):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
WebSocket.__init__(self, sock, protocols=protocols, extensions=extensions)
self.stream.always_mask = True
self.stream.expect_masking = False
self.key = b64encode(os.urandom(16))
self.url = url
示例6: test_cannot_process_more_data_when_stream_is_terminated
def test_cannot_process_more_data_when_stream_is_terminated(self):
m = MagicMock()
ws = WebSocket(sock=m)
ws.client_terminated = True
ws.server_terminated = True
self.assertFalse(ws.once())
示例7: __init__
def __init__(self, app_name, *args, **kw):
self.app_name = app_name
self.backend = get_backend()
self.verbose = self.backend.verbose
cherrypy.log.access_log.info(
'Creating %s with args=%s and keywords=%s.' % (self.app_name, args, kw))
WebSocket.__init__(self, *args, **kw)
self.backend.register(self)
示例8: __init__
def __init__(self, *args, **kwargs):
"""
This passes all arguments to the parent constructor. In addition, it
defines the following instance variables:
send_lock: Used to guarantee thread-safety when sending RPC responses.
client_locks: A dict mapping client ids to locks used by those clients.
passthru_subscriptions: When we recieve a subscription request for a
service method registered on a remote service, we pass that request
along to the remote service and send back the responses. This
dictionary maps client ids to those subscription objects.
session_fields: We copy session data for the currently-authenticated
user who made the incoming websocket connection; by default we only
copy the username, but this can be overridden in configuration.
Remember that Sideboard exposes two websocket handlers at /ws and
/wsrpc, with /ws being auth-protected (so the username field will be
meaningful) and /wsrpc being client-cert protected (so the username
will always be 'rpc').
header_fields: We copy header fields from the request that initiated the
websocket connection.
cached_queries and cached_fingerprints: When we receive a subscription
update, Sideboard re-runs all of the subscription methods to see if
new data needs to be pushed out. We do this by storing all of the
rpc methods and an MD5 hash of their return values. We store a hash
rather than the return values themselves to save on memory, since
return values may be very large.
The cached_queries dict has this structure:
{
'client_id': {
'callback_id': (func, args, kwargs, client_data),
...
},
...
}
The cached_fingerprints dict has this structure:
{
'client_id': {
'callback_id': 'md5_hash_of_return_value',
...
},
...
}
"""
WebSocket.__init__(self, *args, **kwargs)
self.instances.add(self)
self.send_lock = RLock()
self.passthru_subscriptions = {}
self.client_locks = defaultdict(RLock)
self.cached_queries, self.cached_fingerprints = defaultdict(dict), defaultdict(dict)
self.session_fields = self.check_authentication()
self.header_fields = self.fetch_headers()
示例9: closed
def closed(self, code, reason=''):
"""
This overrides the default closed handler to first clean up all of our
subscriptions, remove this websocket from the registry of instances,
and log a message before closing.
"""
log.info('closing: code={!r} reason={!r}', code, reason)
self.instances.discard(self)
self.unsubscribe_all()
WebSocket.closed(self, code, reason)
示例10: test_closing_message_received
def test_closing_message_received(self):
s = MagicMock()
m = MagicMock()
c = MagicMock()
ws = WebSocket(sock=m)
with patch.multiple(ws, close=c):
ws.stream = s
ws.stream.closing = CloseControlMessage(code=1000, reason='test closing')
ws.process(b'unused for this test')
c.assert_called_once_with(1000, b'test closing')
示例11: test_send_bytes_with_masking
def test_send_bytes_with_masking(self):
tm = TextMessage(b'hello world').single(mask=True)
m = MagicMock()
ws = WebSocket(sock=m)
ws.stream = MagicMock()
ws.stream.always_mask = True
ws.stream.text_message.return_value.single.return_value = tm
ws.send(b'hello world')
m.sendall.assert_called_once_with(tm)
示例12: join_queue
def join_queue(socket:WebSocket, data):
# keep this order to avoid state conflict
channel, pubsub = pub_sub_pool.join()
r_queue.put(channel)
# {'pattern': None, 'type': 'message', 'data': b'30ae154a-2397-4945-aeed-48dad6c603b6', 'channel': 'queue_channel:19'}
msg = pub_sub_pool.next_message(channel, pubsub)
uid = msg['data']
if not uid in games:
games[uid] = make_game_engine()
games[uid].join_game(data["player"])
socket.send(uid)
示例13: __init__
def __init__(self, *args, **kw):
WebSocket.__init__(self, *args, **kw)
# cherrypy.log("args type %s" % type(ws))
#
# for i in args:
# try:
# cherrypy.log("args %s \n" % i)
# except Exception as error:
# cherrypy.log("Can't print args because %s \n" % error)
# cherrypy.log("args %s " % args)
# cherrypy.log("kw %s " % kw)
SUBSCRIBERS.add(self)
示例14: send
def send(self, **message):
message = {k: v for k, v in message.items() if v is not None}
if "data" in message and "client" in message:
fingerprint = _fingerprint(message["data"])
client, callback = message["client"], message.get("callback")
repeat_send = callback in self.cached_fingerprints[client]
cached_fingerprint = self.cached_fingerprints[client].get(callback)
self.cached_fingerprints[client][callback] = fingerprint
if cached_fingerprint == fingerprint and repeat_send:
return
self.log.debug("sending {}", message)
message = json.dumps(message, cls=sideboard.lib.serializer, separators=(",", ":"), sort_keys=True)
with self.send_lock:
WebSocket.send(self, message)
示例15: test_send_generator_without_masking
def test_send_generator_without_masking(self):
tm0 = b'hello'
tm1 = b'world'
def datasource():
yield tm0
yield tm1
gen = datasource()
m = MagicMock()
ws = WebSocket(sock=m)
ws.send(gen)
self.assertEqual(m.sendall.call_count, 2)
self.assertRaises(StopIteration, next, gen)