本文整理汇总了Python中ws4py.client.threadedclient.WebSocketClient.close方法的典型用法代码示例。如果您正苦于以下问题:Python WebSocketClient.close方法的具体用法?Python WebSocketClient.close怎么用?Python WebSocketClient.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ws4py.client.threadedclient.WebSocketClient
的用法示例。
在下文中一共展示了WebSocketClient.close方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WebSocektRFC6455
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
class WebSocektRFC6455(object):
def __init__(self, url):
self.ws = WebSocketClient(url)
self.queue = Queue.Queue()
def onmessage(m):
print "received: %s" % m
self.queue.put(unicode(str(m), 'utf-8'))
self.ws.received_message = onmessage
def connect(self):
self.ws.connect()
return self
def send(self, msg):
self.ws.send(msg)
return self
def recv(self, timeout=1.0):
try:
return self.queue.get(timeout=timeout)
except Queue.Empty:
raise TimeoutException("websocket didn't receive any thing")
def close(self):
self.ws.close()
示例2: close
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def close(self, code=1000, reason=''):
try:
WebSocketClient.close(self, code=code, reason=reason)
except:
pass
try:
WebSocketClient.close_connection(self)
except:
pass
self.connected = False
示例3: skim_test_4_1_2
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def skim_test_4_1_2(n_topics=10):
# test 'globals'
subLock = threading.Lock()
subscriptions = dict()
def received_message(m):
data = json.loads(m.data)
if data['op'] == 'publish':
r_topic = data['topic']
r_msg = json.dumps(data['msg'])
with subLock:
for sub in subscriptions.itervalues():
if r_topic == sub['topic']:
sub['callback'](r_msg)
ws = WebSocketClient(ROSBRIDGE_HOST)
ws.received_message = received_message
ws.connect()
current_subID = 1
for i_top in xrange(n_topics):
# RUN: One Topic (per topic code)
topicArrived = threading.Event()
topicArrived.clear()
def genf(i_topic=0):
return lambda data: topicArrived.set()
# Subscribe
subID = current_subID
current_subID += 1
msg = {'op': 'subscribe', 'topic': SUBTOPIC,
'type': MSGTYPE, 'id': subID, 'throttle_rate': 5}
ws.send(json.dumps(msg))
with subLock:
subscriptions[subID] = {'callback': genf(i_top),
'topic': SUBTOPIC}
# Wait for Msg
got_msg = topicArrived.wait(2.0)
# Unsubscribe
msg = {'op': 'unsubscribe', 'id': subID, 'topic': SUBTOPIC}
with subLock:
del subscriptions[subID]
ws.send(json.dumps(msg))
sleep(0.01) # 0.1 doesn't seem to cause the problem (after 20hr)...
ws.close()
示例4: test_4_1
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def test_4_1(n_topics=10):
if 1:
ws = WebSocketClient(ROSBRIDGE_HOST)
else:
ws = RosBridgeClient(ROSBRIDGE_HOST)
ws.connect()
topicArrived = threading.Event()
for i_top in xrange(n_topics):
topicArrived.clear()
def genf(i_topic=0):
return lambda data: topicArrived.set()
subID = ws.subscribe(SUBTOPIC, MSGTYPE, genf(i_top))
got_msg = topicArrived.wait(2.0)
ws.unsubscribe(subID)
ws.close()
示例5: Client
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
class Client(object):
def __init__(self, listener):
self.listener = listener
self._ws_url = 'wss://ws.bitso.com'
self.ws_client = WebSocketClient(self._ws_url)
self.ws_client.opened = self.listener.on_connect
self.ws_client.received_message = self._received
self.ws_client.closed = self._closed
self.channels = []
def connect(self, channels):
self.channels = channels
self.ws_client.opened = self._opened
self.ws_client.connect()
self.ws_client.run_forever()
def close(self):
self.ws_client.close()
def _opened(self):
for channel in self.channels:
self.ws_client.send(json.dumps({ 'action': 'subscribe', 'book': 'btc_mxn', 'type': channel }))
thread.start_new_thread(self._ping_server, ())
self.listener.on_connect()
def _received(self, m):
#print m.data
val = json.loads(m.data)
obj = StreamUpdate(val)
self.listener.on_update(obj)
def _closed(self, code, reason):
self.listener.on_close(code, reason)
def _ping_server(self):
while True:
#keep-alive
self.ws_client.send(PingControlMessage(u'ping'))
time.sleep(20)
示例6: crd_open_url
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def crd_open_url(host, url):
""" Opens URL (developer mode only)
If your Chromecast device is whitelisted, make
embedded browser navigate to url."""
try:
# ask Chrome debugger interface for api endpoint
resp = requests.get(FORMAT_DEBUG_URL.format(host))
except requests.exceptions.ConnectionError:
return False
payload = json.loads(resp.text)
wsurl = payload[0]['webSocketDebuggerUrl']
# format and send api navigate command to the endpoint
debugcom = FORMAT_CMD.format(url)
remws = WebSocketClient(wsurl)
remws.connect()
remws.send(debugcom)
remws.close()
return True
示例7: close
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def close(self, code=1001, reason=None):
if not self._connected:
return
WebSocketClient.close(self, code, reason)
示例8: hack_test_4_1_2
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def hack_test_4_1_2(n_topics=10):
# test 'globals'
subLock = threading.Lock()
subscriptions = dict()
def received_message(m):
data = json.loads(m.data)
if data['op'] == 'publish':
r_topic = data['topic']
r_msg = json.dumps(data['msg'])
# print data
# print data.keys()
with subLock:
for sub in subscriptions.itervalues():
if r_topic == sub['topic']:
sub['callback'](r_msg)
w_type = 2
if w_type==1:
ws = WebSocketClient(ROSBRIDGE_HOST)
elif w_type==2:
ws = WebSocketClient(ROSBRIDGE_HOST)
ws.received_message = received_message
# elif w_type==3:
# ws = WebSocketClient(ROSBRIDGE_HOST)
# def received_message(self, m):
# data = json.loads(m.data)
# if data['op'] == 'publish':
# r_topic = data['topic']
# r_msg = json.dumps(data['msg'])
#
# self.subLock.acquire(True)
# for sub in self.subscriptions.itervalues():
# if r_topic == sub['topic']:
# sub['callback'](r_msg)
# self.subLock.release()
# # ws.received_message = received_message
else:
ws = RosBridgeClient(ROSBRIDGE_HOST)
ws.connect()
# subLock = threading.Lock()
# subscriptions = dict()
current_subID = 1
for i_top in xrange(n_topics):
# RUN: One Topic (per topic code)
topicArrived = threading.Event()
topicArrived.clear()
def genf(i_topic=0):
return lambda data: topicArrived.set()
# subID = ws.subscribe(SUBTOPIC, MSGTYPE, genf())
def subscribe(current_subID, topic, messageType, callback):
subID = current_subID
current_subID += 1
msg = {'op': 'subscribe', 'topic': SUBTOPIC,
'type': MSGTYPE, 'id': subID, 'throttle_rate': 5}
ws.send(json.dumps(msg))
with subLock:
subscriptions[subID] = {'callback': callback, 'topic': SUBTOPIC}
return subID
subID = subscribe(current_subID, SUBTOPIC, MSGTYPE, genf(i_top))
got_msg = topicArrived.wait(2.0)
# ws.unsubscribe(subID)
def unsubscribe(subID):
msg = {'op': 'unsubscribe', 'id': subID, 'topic': SUBTOPIC}
with subLock:
del subscriptions[subID]
ws.send(json.dumps(msg))
unsubscribe(subID)
ws.close()
示例9: close
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def close(self,force=False):
WebSocketClient.close(self)
self.client_terminated = True
if force: self.close_connection()
示例10: close
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
def close(self, code=1000, reason=''):
WebSocketClient.close(self, code, reason)
示例11: Client
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
#.........这里部分代码省略.........
if members[i].id == owner:
owner = members[i]
for presence in guild['presences']:
user_id = presence['user']['id']
member = utils.find(lambda m: m.id == user_id, members)
if member is not None:
member.status = presence['status']
member.game_id = presence['game_id']
server = Server(owner=owner, **guild)
# give all the members their proper server
for member in server.members:
member.server = server
channels = [Channel(server=server, **channel) for channel in guild['channels']]
server.channels = channels
self.servers.append(server)
def _create_websocket(self, url, reconnect=False):
if url is None:
raise GatewayNotFound()
log.info('websocket gateway found')
self.ws = WebSocketClient(url, protocols=['http-only', 'chat'])
# this is kind of hacky, but it's to avoid deadlocks.
# i.e. python does not allow me to have the current thread running if it's self
# it throws a 'cannot join current thread' RuntimeError
# So instead of doing a basic inheritance scheme, we're overriding the member functions.
self.ws.opened = self._opened
self.ws.closed = self._closed
self.ws.received_message = self._received_message
self.ws.connect()
log.info('websocket has connected')
if reconnect == False:
second_payload = {
'op': 2,
'd': {
'token': self.token,
'properties': {
'$os': sys.platform,
'$browser': 'discord.py',
'$device': 'discord.py',
'$referrer': '',
'$referring_domain': ''
},
'v': 2
}
}
self.ws.send(json.dumps(second_payload))
def _resolve_mentions(self, content, mentions):
if isinstance(mentions, list):
return [user.id for user in mentions]
elif mentions == True:
return re.findall(r'<@(\d+)>', content)
else:
return []
def _invoke_event(self, event_name, *args, **kwargs):
try:
示例12: Client
# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import close [as 别名]
class Client(object):
"""Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the :class:`Client` via keyword arguments.
:param int max_length: The maximum number of messages to store in :attr:`messages`. Defaults to 5000.
Instance attributes:
.. attribute:: user
A :class:`User` that represents the connected client. None if not logged in.
.. attribute:: servers
A list of :class:`Server` that the connected client has available.
.. attribute:: private_channels
A list of :class:`PrivateChannel` that the connected client is participating on.
.. attribute:: messages
A deque_ of :class:`Message` that the client has received from all servers and private messages.
.. _deque: https://docs.python.org/3.4/library/collections.html#collections.deque
"""
def __init__(self, **kwargs):
self._is_logged_in = False
self.user = None
self.servers = []
self.private_channels = []
self.token = ""
self.messages = deque([], maxlen=kwargs.get("max_length", 5000))
self.events = {
"on_ready": _null_event,
"on_disconnect": _null_event,
"on_error": _null_event,
"on_response": _null_event,
"on_message": _null_event,
"on_message_delete": _null_event,
"on_message_edit": _null_event,
"on_status": _null_event,
"on_channel_delete": _null_event,
"on_channel_create": _null_event,
"on_member_join": _null_event,
"on_member_remove": _null_event,
"on_member_typing": _null_event,
}
gateway = requests.get(endpoints.GATEWAY)
if gateway.status_code != 200:
raise GatewayNotFound()
gateway_js = gateway.json()
url = gateway_js.get("url")
if url is None:
raise GatewayNotFound()
self.ws = WebSocketClient(url, protocols=["http-only", "chat"])
# this is kind of hacky, but it's to avoid deadlocks.
# i.e. python does not allow me to have the current thread running if it's self
# it throws a 'cannot join current thread' RuntimeError
# So instead of doing a basic inheritance scheme, we're overriding the member functions.
self.ws.opened = self._opened
self.ws.closed = self._closed
self.ws.received_message = self._received_message
# the actual headers for the request...
# we only override 'authorization' since the rest could use the defaults.
self.headers = {"authorization": self.token}
def _get_message(self, msg_id):
return next((m for m in self.messages if m.id == msg_id), None)
def _get_server(self, guild_id):
return next((s for s in self.servers if s.id == guild_id), None)
def _get_channel(self, channel_id):
return next((c for c in server.channels if c.id == channel_id), None)
def _get_member(self, user_id):
return next((m for m in server.members if m.id == user_id), None)
def _resolve_mentions(self, content, mentions):
if isinstance(mentions, list):
return [user.id for user in mentions]
elif mentions == True:
return re.findall(r"@<(\d+)>", content)
else:
return []
def _invoke_event(self, event_name, *args, **kwargs):
try:
self.events[event_name](*args, **kwargs)
except Exception as e:
pass
def _received_message(self, msg):
response = json.loads(str(msg))
#.........这里部分代码省略.........