Python源码示例:websocket.WebSocketApp()
示例1
def connect(self, apiKey, secretKey, trace=False):
self.host = OKEX_USD_CONTRACT
self.apiKey = apiKey
self.secretKey = secretKey
self.trace = trace
websocket.enableTrace(trace)
self.ws = websocket.WebSocketApp(self.host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target=self.ws.run_forever, args=(None, None, 60, 30))
self.thread.start()
# ----------------------------------------------------------------------
示例2
def run(self):
token = self.client['config/auth.token']
device_id = self.client['config/app.device_id']
server = self.client['config/auth.server']
server = server.replace('https', "wss") if server.startswith('https') else server.replace('http', "ws")
wsc_url = "%s/embywebsocket?api_key=%s&device_id=%s" % (server, token, device_id)
LOG.info("Websocket url: %s", wsc_url)
self.wsc = websocket.WebSocketApp(wsc_url,
on_message=self.on_message,
on_error=self.on_error)
self.wsc.on_open = self.on_open
while not self.stop:
self.wsc.run_forever(ping_interval=10)
if self.stop:
break
time.sleep(5)
self.client['callback_ws']('WebSocketRestarting')
LOG.info("---<[ websocket ]")
示例3
def testSockMaskKey(self):
""" A WebSocketApp should forward the received mask_key function down
to the actual socket.
"""
def my_mask_key_func():
pass
def on_open(self, *args, **kwargs):
""" Set the value so the test can use it later on and immediately
close the connection.
"""
WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
self.close()
app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
app.run_forever()
# if numpu is installed, this assertion fail
# Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
# self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
示例4
def _connect(self):
self._log.debug('初始化websocket并发起链接')
self._socket = websocket.WebSocketApp(
self._url,
on_open=self._on_open,
on_message=self._on_message,
on_close=self._on_close,
on_error=self._on_error
)
self._socket.run_forever()
# 以下用于重连
while self._reconnect_required.is_set():
if not self._disconnecte_required.is_set():
self._socket.sock = None
delay = self._reconnect_interval
while delay > 0:
self._log.info('%ds 后重连' % delay)
time.sleep(1)
delay -= 1
self._socket.keep_running = True
self._socket.run_forever()
示例5
def reconnect(self):
"""重新连接"""
# 首先关闭之前的连接
#self.close()
# 再执行重连任务
self.ws = websocket.WebSocketApp(self.host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target=self.ws.run_forever , args = (None , None , 60, 30))
self.thread.start()
#----------------------------------------------------------------------
示例6
def connect_Subpot(self, apiKey , secretKey , trace = False):
self.host = GATEIO_SOCKET_URL
self.apiKey = apiKey
self.secretKey = secretKey
self.trace = trace
websocket.enableTrace(trace)
self.ws = websocket.WebSocketApp(self.host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target = self.ws.run_forever , args = (None , None , 60, 30))
# self.thread_heart = Thread(target = self.run_forever_heart)
self.thread.start()
# self.thread_heart.start()
#----------------------------------------------------------------------
示例7
def reconnect(self):
"""重新连接"""
# 首先关闭之前的连接
#self.close()
# 再执行重连任务
self.ws = websocket.WebSocketApp(self.host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target=self.ws.run_forever , args = (None , None , 60, 30))
self.thread.start()
#----------------------------------------------------------------------
示例8
def connect_Subpot(self , trace = False):
self.host = FCOIN_WSS_HOST
self.trace = trace
websocket.enableTrace(trace)
self.ws = websocket.WebSocketApp(self.host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target = self.ws.run_forever , args = (None , None , 60, 30))
# self.thread_heart = Thread(target = self.run_forever_heart)
self.thread.start()
# self.thread_heart.start()
#----------------------------------------------------------------------
示例9
def api_connect(self, url):
# Proxy support adapted from the UStreamTV plugin (ustreamtv.py)
proxy_url = self.session.get_option("https-proxy")
if proxy_url is None:
proxy_url = self.session.get_option("http-proxy")
proxy_options = parse_proxy_url(proxy_url)
if proxy_options.get('http_proxy_host'):
_log.debug("Using proxy ({0}://{1}:{2})".format(
proxy_options.get('proxy_type') or "http",
proxy_options.get('http_proxy_host'),
proxy_options.get('http_proxy_port') or 80))
_log.debug("Connecting: {0}".format(url))
self._ws = websocket.WebSocketApp(
url,
header=["User-Agent: {0}".format(useragents.CHROME)],
on_open=self.api_on_open,
on_message=self.handle_api_message,
on_error=self.api_on_error)
self.ws_worker_thread = threading.Thread(
target=self._ws.run_forever,
args=proxy_options)
self.ws_worker_thread.daemon = True
self.ws_worker_thread.start()
示例10
def testSockMaskKey(self):
""" A WebSocketApp should forward the received mask_key function down
to the actual socket.
"""
def my_mask_key_func():
pass
def on_open(self, *args, **kwargs):
""" Set the value so the test can use it later on and immediately
close the connection.
"""
WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
self.close()
app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
app.run_forever()
# if numpu is installed, this assertion fail
# Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
# self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))
示例11
def run_subscription_batch_jobs(self):
"""
请求 KLine 实时数据
"""
websocket.enableTrace(False)
self.__ws = websocket.WebSocketApp(
self.HUOBIPRO_WEBSOCKET_URL,
on_message=self.on_message,
on_open=self.on_open,
on_error=self.on_error,
on_close=self.on_close
)
self.__locked = True
# 如果意外退出,等待10秒重新运行
while (True):
self.__ws.run_forever()
QA_util_log_expection("FTW! it quit! Retry 10 seconds later...")
time.sleep(10)
示例12
def run(self):
self.topic_type = wait_topic_ready(self.topic_name, self.url)
#print str(self.topic_type)+" self.topic_type"
if not self.topic_type:
rospy.logerr('Type of topic %s are not equal in the remote and local sides', self.topic_name)
return
topic_type_module, topic_type_name = tuple(self.topic_type.split('/'))
try:
roslib.load_manifest(topic_type_module)
msg_module = import_module(topic_type_module + '.msg')
self.rostype = getattr(msg_module, topic_type_name)
if self.test:
self.publisher = rospy.Publisher(self.topic_name + '_rb', self.rostype, queue_size = self.queue_size)
else:
self.publisher = rospy.Publisher(self.topic_name, self.rostype, queue_size = self.queue_size)
self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
rospy.loginfo('Create connection to Rosbridge server %s for subscribed topic %s successfully', self.url, self.topic_name)
self.ws.run_forever()
except ResourceNotFound, e:
rospy.logerr('Proxy for subscribed topic %s init falied. Reason: Could not find the required resource: %s', self.topic_name, str(e))
示例13
def run(self):
self.service_type, self.service_args = wait_service_ready(self.service_name, self.url)
if not self.service_type:
rospy.logerr('Type of service %s are not equal in the remote and local sides', self.service_type)
return
service_type_module, service_type_name = tuple(self.service_type.split('/'))
try:
roslib.load_manifest(service_type_module)
msg_module = import_module(service_type_module + '.srv')
self.srvtype = getattr(msg_module, service_type_name)
if self.test:
self.caller = rospy.Service(self.service_name + '_rb', self.srvtype, self.callback)#, self.queue_size)
else:
self.caller = rospy.Service(self.service_name, self.srvtype, self.callback)#, self.queue_size)
self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
rospy.loginfo('Create connection to Rosbridge server %s for calling service %s successfully', self.url, self.service_name)
self.ws.run_forever()
except ResourceNotFound, e:
rospy.logerr('Proxy for service %s init falied. Reason: Could not find the required resource: %s', self.service_name, str(e))
示例14
def run(self):
self.topic_type = wait_topic_ready(self.topic_name, self.url)
if not self.topic_type:
rospy.logerr('Type of topic %s are not equal in the remote and local sides', self.topic_name)
return
topic_type_module, topic_type_name = tuple(self.topic_type.split('/'))
try:
roslib.load_manifest(topic_type_module)
msg_module = import_module(topic_type_module + '.msg')
self.rostype = getattr(msg_module, topic_type_name)
self.subscriber = rospy.Subscriber(self.topic_name, self.rostype, self.callback)
self.ws = websocket.WebSocketApp(self.url, on_message = self.on_message, on_error = self.on_error, on_close = self.on_close, on_open = self.on_open)
rospy.loginfo('Create connection to Rosbridge server for published topic %s successfully', self.topic_name)
self.ws.run_forever()
except ResourceNotFound, e:
rospy.logerr('Could not find the required resource %s', str(e))
示例15
def _run(ws, id):
"""
Takes user input and sends it to a websocket.
:param ws: websocket.WebSocketApp
"""
while True:
x = input("\033[44m Me: ")
print("\033[0m", end="")
data = {}
data['id'] = id
data['text'] = x
json_data = json.dumps(data)
ws.send(json_data)
time.sleep(1)
if x == "[DONE]":
break
ws.close()
示例16
def startWebsocket(self):
""" Run the websocket in a thread """
self._tick = {}
iniTick = self.returnTicker()
self._ids = {market: iniTick[market]['id'] for market in iniTick}
for market in iniTick:
self._tick[self._ids[market]] = iniTick[market]
self._ws = WebSocketApp("wss://api2.poloniex.com/",
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close)
self._t = _Thread(target=self._ws.run_forever)
self._t.daemon = True
self._t._running = True
self._t.start()
logger.info('Websocket thread started')
logger.debug(self._ws.url)
示例17
def __init__(self, host: str, port: int, connect_timeout: Optional[float] = None,
password: Optional[str] = None, ws: Optional[websocket.WebSocketApp] = None):
self.host = host
self.port = port
self.connect_timeout = connect_timeout
self.password = password
self.state = self.State.DISCONNECTED
self.ws = ws
self._connected = threading.Event()
self._logged_in = threading.Event()
self._echo_received = threading.Event()
self._response_received = threading.Event()
self._download_chunk_ready = threading.Event()
self._file_transfer_request_ack_received = threading.Event()
self._file_transfer_ack_received = threading.Event()
self._file_transfer_request_successful = True
self._file_transfer_successful = True
self._downloaded_chunks = queue.Queue()
self._password_requested = False
self._running_cmd = None
self._received_echo = None
self._received_response = None
self._paste_header_received = False
self.logger = logging.getLogger(__name__)
示例18
def __init__(self, test=False):
"""
constructor
"""
self.testnet = test
if test:
domain = 'testnet.bitmex.com'
else:
domain = 'www.bitmex.com'
self.endpoint = 'wss://' + domain + '/realtime?subscribe=tradeBin1m:XBTUSD,' \
'tradeBin5m:XBTUSD,tradeBin1h:XBTUSD,tradeBin1d:XBTUSD,instrument:XBTUSD,' \
'margin,position:XBTUSD,wallet,orderBookL2:XBTUSD'
self.ws = websocket.WebSocketApp(self.endpoint,
on_message=self.__on_message,
on_error=self.__on_error,
on_close=self.__on_close,
header=self.__get_auth())
self.wst = threading.Thread(target=self.__start)
self.wst.daemon = True
self.wst.start()
示例19
def __on_close(self, ws):
"""
On Close Listener
:param ws:
"""
if 'close' in self.handlers:
self.handlers['close']()
if self.is_running:
logger.info("Websocket restart")
notify(f"Websocket restart")
self.ws = websocket.WebSocketApp(self.endpoint,
on_message=self.__on_message,
on_error=self.__on_error,
on_close=self.__on_close,
header=self.__get_auth())
self.wst = threading.Thread(target=self.__start)
self.wst.daemon = True
self.wst.start()
示例20
def websocket_func(*args):
try:
websocket_manage = args[0]
websocket_manage.original_connection = websocket.WebSocketApp(websocket_manage.url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
global websocket_connection_handler
websocket_connection_handler[websocket_manage.original_connection] = websocket_manage
websocket_manage.logger.info("[Sub][" + str(websocket_manage.id) + "] Connecting...")
websocket_manage.original_connection.on_open = on_open
websocket_manage.original_connection.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
websocket_manage.logger.info("[Sub][" + str(websocket_manage.id) + "] Connection event loop down")
if websocket_manage.state == ConnectionState.CONNECTED:
websocket_manage.state = ConnectionState.IDLE
except Exception as ex:
print(ex)
示例21
def _websocketThread(self, evtThreadEnded):
try:
websocket.enableTrace(False)
self._ws = websocket.WebSocketApp(self._REST_URLS['websocket'] + self.access_token,
on_open=self._on_open,
on_message=self._on_message,
on_close=self._on_close,
on_error=self._on_error)
# ping_timeout is for no blocking call
self._ws.run_forever(ping_interval=self.ping_timeout/2, ping_timeout=self.ping_timeout)
except AttributeError:
self._on_error(websocket, 'No internet connection!')
except Exception as ex:
self._on_error(websocket, ex)
finally:
evtThreadEnded.set()
示例22
def connect(self, host, apiKey, secretKey, trace=False):
"""连接服务器"""
self.host = host
self.apiKey = apiKey
self.secretKey = secretKey
if self.host == OKCOIN_CNY:
self.currency = CURRENCY_CNY
else:
self.currency = CURRENCY_USD
websocket.enableTrace(trace)
self.ws = websocket.WebSocketApp(host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target=self.ws.run_forever)
self.thread.start()
#----------------------------------------------------------------------
示例23
def connect(self, host, apiKey, secretKey, trace=False):
"""连接服务器"""
self.host = host
self.apiKey = apiKey
self.secretKey = secretKey
if self.host == OKCOIN_CNY:
self.currency = CURRENCY_CNY
else:
self.currency = CURRENCY_USD
websocket.enableTrace(trace)
self.ws = websocket.WebSocketApp(host,
on_message=self.onMessage,
on_error=self.onError,
on_close=self.onClose,
on_open=self.onOpen)
self.thread = Thread(target=self.ws.run_forever)
self.thread.start()
#----------------------------------------------------------------------
示例24
def _connect(self):
self.state = "connecting"
self.socket = websocket.WebSocketApp(
self.url,
on_open=self._on_open,
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close
)
self.socket.run_forever(**self.socket_kwargs)
while self.needs_reconnect and not self.disconnect_called:
self.logger.info("Attempting to connect again in %s seconds."
% self.reconnect_interval)
self.state = "unavailable"
time.sleep(self.reconnect_interval)
# We need to set this flag since closing the socket will set it to
# false
self.socket.keep_running = True
self.socket.run_forever(**self.socket_kwargs)
示例25
def __connect(self, wsURL, symbol):
'''Connect to the websocket in a thread.'''
self.logger.debug("Starting thread")
self.ws = websocket.WebSocketApp(wsURL,
on_message=self.__on_message,
on_close=self.__on_close,
on_open=self.__on_open,
on_error=self.__on_error,
header=self.__get_auth())
self.wst = threading.Thread(target=lambda: self.ws.run_forever())
self.wst.daemon = True
self.wst.start()
self.logger.debug("Started thread")
# Wait for connect before continuing
conn_timeout = 5
while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
sleep(1)
conn_timeout -= 1
if not conn_timeout:
self.logger.error("Couldn't connect to WS! Exiting.")
self.exit()
raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')
示例26
def connect(self):
self.logger.info("connect ws")
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("wss://www.deribit.com/ws/api/v1/",
on_message = lambda ws,msg: self.on_message(ws, msg),
on_error = lambda ws,msg: self.on_error(ws, msg),
on_open = lambda ws: self.on_open(ws),
#on_open = self.on_open,
on_close = self.on_close)
ssl_defaults = ssl.get_default_verify_paths()
sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
self.wst = threading.Thread(target=lambda: self.ws.run_forever(sslopt=sslopt_ca_certs))
self.wst.daemon = True
self.wst.start()
self.logger.info("Started thread")
#TOOD subscribe later
#self.ws.run_forever()
示例27
def __init__(self, sonoff, on_message=None, on_error=None):
self.logger = sonoff.logger
self._sonoff = sonoff
websocket_host = 'ws://{}:{}{}'.format(self._sonoff.get_wshost(),
self._sonoff.get_wsport(),
self._sonoff.get_wsendpoint())
self.logger.info('WebsocketListener initialising, connecting to host: %s' % websocket_host)
threading.Thread.__init__(self)
websocket.WebSocketApp.__init__(self, websocket_host,
on_open=self.on_open,
on_error=on_error,
on_message=on_message,
on_close=self.on_close)
self.connected = False
self.last_update = time.time()
示例28
def run_forever(self):
"""Run the bot, blocking forever."""
res = self.slack.rtm.start()
self.log.info("current channels: %s",
','.join(c['name'] for c in res.body['channels']
if c['is_member']))
self.id = res.body['self']['id']
self.name = res.body['self']['name']
self.my_mention = "<@%s>" % self.id
self.ws = websocket.WebSocketApp(
res.body['url'],
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close,
on_open=self._on_open)
self.prepare_connection(self.config)
self.ws.run_forever()
示例29
def main():
# Connect to websocket interfaces
headers = {}
userpass = ":".join(get_auth())
headers["Authorization"] = "Basic " + base64.b64encode(
userpass.encode()).decode()
url = get_url()
# If you really want to see everything going across the wire,
# uncomment this. However realize the trace is going to also do
# things like dump the binary sound packets in text in the
# console.
#
# websocket.enableTrace(True)
ws = websocket.WebSocketApp(url,
header=headers,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.args = parse_args()
# This gives control over the WebSocketApp. This is a blocking
# call, so it won't return until the ws.close() gets called (after
# 6 seconds in the dedicated thread).
ws.run_forever()
示例30
def ws_request(self, url, headers=None, **kwargs):
if self.debug:
print("Open {}".format(url))
if headers is None:
headers = {}
else:
headers = headers.copy()
def on_error(ws, x):
ws.error = x
for provider in self.token_providers:
if not provider.is_applicable():
continue
token = provider.get_token()
headers.update({'Authorization': 'Bearer {}'.format(token)})
ws = websocket.WebSocketApp(url, header=headers, **kwargs)
ws.error = None
ws.on_error = on_error
ws.run_forever()
if ws.error is None:
# Websocket connection was terminated cleanly.
break
elif isinstance(ws.error, KeyboardInterrupt):
# User used Ctrl+C to terminate the session.
break