Python websocket 模块 WebSocketApp 长连接方法新老版本不兼容

本文主要是介绍Python websocket 模块 WebSocketApp 长连接方法新老版本不兼容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

____tz_zs

websocket 库在 0.48.0 版本后对回调进行了修改。
新版本中,当我们将一个实例对象的方法作为 WebSocketApp 的回调时,WebSocketApp 将不再会返回他自己作为回调的第一个参数。

普通方法作为 WebSocketApp 回调

以下为官方示例的长连接用法 Long-lived connection,此种方式在新老版本中均能正常使用。

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""import websockettry:import thread
except ImportError:import _thread as thread
import timeurl = "ws://echo.websocket.org/"def on_message(ws, message):print("####### on_message #######")print(ws)print(message)def on_error(ws, error):print("####### on_error #######")print(ws)print(error)def on_close(ws):print("####### on_close #######")print(ws)print("####### closed #######")def on_open(ws):print("####### on_open #######")def run(*args):for i in range(3):time.sleep(1)ws.send("Hello %d" % i)time.sleep(1)ws.close()print("thread terminating...")thread.start_new_thread(run, ())if __name__ == '__main__':ws = websocket.WebSocketApp(url,on_message=on_message,on_error=on_error,on_close=on_close)ws.on_open = on_openws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)"""
####### on_open #######
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f8ffe73eb38>
Hello 0
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f8ffe73eb38>
Hello 1
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f8ffe73eb38>
Hello 2
####### on_close #######
<websocket._app.WebSocketApp object at 0x7f8ffe73eb38>
thread terminating...
####### closed #######
"""

对象的方法作为 WebSocketApp 回调

注意,下方代码中的 Test 不是 WebSocketApp 的子类。
版本 0.48.0 之前能如下方式使用,这种方式比较灵活,

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""import websockettry:import thread
except ImportError:import _thread as thread
import timeclass Test(object):def __init__(self):self.url = "ws://echo.websocket.org/"def on_message(self, ws, message):print("on_message")print(self)print(ws)print(message)def on_error(self, ws, error):print("on_error")print(self)print(ws)print(error)def on_close(self, ws):print("on_close")print(self)print(ws)print("### closed ###")def on_open(self, ws):def run(*args):for i in range(3):time.sleep(1)ws.send("Hello %d" % i)time.sleep(1)ws.close()print("thread terminating...")thread.start_new_thread(run, ())def start(self):ws = websocket.WebSocketApp(self.url,on_message=self.on_message,on_error=self.on_error,on_close=self.on_close)ws.on_open = self.on_openws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)if __name__ == '__main__':Test().start()"""
on_message
<__main__.Test object at 0x7ffa6409e908>
<websocket._app.WebSocketApp object at 0x7ffa6409eb70>
Hello 0
on_message
<__main__.Test object at 0x7ffa6409e908>
<websocket._app.WebSocketApp object at 0x7ffa6409eb70>
Hello 1
on_message
<__main__.Test object at 0x7ffa6409e908>
<websocket._app.WebSocketApp object at 0x7ffa6409eb70>
Hello 2
on_close
thread terminating...
<__main__.Test object at 0x7ffa6409e908>
<websocket._app.WebSocketApp object at 0x7ffa6409eb70>
### closed ###
"""

但当升级为新版本后(0.48.0 版之后),这种方式不再兼容,具体原因:
新版本中,当我们将一个实例对象的方法作为 WebSocketApp 的回调时,WebSocketApp 将不再会返回他自己作为回调的第一个参数。

如果设置 log 等级为 DEBUG,可看到以下信息

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""from websocket import WebSocketApptry:import thread
except ImportError:import _thread as thread
import time
import logging
import syslogging.basicConfig(level=logging.DEBUG,format='asctime:        %(asctime)s \n'  # 时间'filename_line:  %(filename)s_[line:%(lineno)d] \n'  # 文件名_行号'level:          %(levelname)s \n'  # log级别'message:        %(message)s \n',  # log信息datefmt='%a, %d %b %Y %H:%M:%S',stream=sys.stdout,filemode='w')class Test(object):def __init__(self):self.url = "ws://echo.websocket.org/"def on_message(self, ws, message):print("on_message")print(self)print(ws)print(message)def on_error(self, ws, error):print("on_error")print(self)print(ws)print(error)def on_close(self, ws):print("on_close")print(self)print(ws)print("### closed ###")def on_open(self, ws):def run(*args):for i in range(3):time.sleep(1)ws.send("Hello %d" % i)time.sleep(1)ws.close()print("thread terminating...")thread.start_new_thread(run, ())def start(self):ws = WebSocketApp(self.url,on_message=self.on_message,on_error=self.on_error,on_close=self.on_close)ws.on_open = self.on_openws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)if __name__ == '__main__':Test().start()"""
asctime:        Thu, 11 Jul 2019 15:22:16 
filename_line:  _logging.py_[line:69] 
level:          DEBUG 
message:        Connecting proxy... File "/usr/local/lib/python3.5/dist-packages/websocket/_app.py", line 343, in _callbackcallback(*args)
asctime:        Thu, 11 Jul 2019 15:22:17 
filename_line:  _logging.py_[line:61] 
level:          ERROR 
message:        error from callback <bound method Test.on_open of <__main__.Test object at 0x7fb68a72ec88>>: on_open() missing 1 required positional argument: 'ws' asctime:        Thu, 11 Jul 2019 15:23:00 
filename_line:  _logging.py_[line:61] 
level:          ERROR 
message:        error from callback <bound method Test.on_error of <__main__.Test object at 0x7fb68a72ec88>>: on_error() missing 1 required positional argument: 'error' File "/usr/local/lib/python3.5/dist-packages/websocket/_app.py", line 343, in _callbackcallback(*args)
asctime:        Thu, 11 Jul 2019 15:23:00 
filename_line:  _logging.py_[line:61] 
level:          ERROR 
message:        error from callback <bound method Test.on_close of <__main__.Test object at 0x7fb68a72ec88>>: on_close() missing 1 required positional argument: 'ws' File "/usr/local/lib/python3.5/dist-packages/websocket/_app.py", line 343, in _callbackcallback(*args)
"""

对于新版本,我们可以采用以下几种方法

新版 对象的方法作为 WebSocketApp 回调

因为新版库不再返回 WebSocketApp 本身,所以参数不再包括 ws,我们保存 WebSocketApp 对象作为实例的一个参数 self.ws,如此,仍可在类中的任意位置使用。

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""import websocket
from websocket import WebSocketApptry:import thread
except ImportError:import _thread as thread
import timeclass Test(object):def __init__(self):super(Test, self).__init__()self.url = "ws://echo.websocket.org/"self.ws = Nonedef on_message(self, message):print("####### on_message #######")print(self)print(message)def on_error(self, error):print("####### on_error #######")print(self)print(error)def on_close(self):print("####### on_close #######")print(self)print("####### closed #######")def on_open(self):print(self)def run(*args):for i in range(3):time.sleep(1)self.ws.send("Hello %d" % i)time.sleep(1)self.ws.close()print("thread terminating...")thread.start_new_thread(run, ())def start(self):self.ws = WebSocketApp(self.url,on_message=self.on_message,on_error=self.on_error,on_close=self.on_close)self.ws.on_open = self.on_openself.ws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)if __name__ == '__main__':Test().start()"""
<__main__.Test object at 0x7fb4e855cb70>
####### on_message #######
<__main__.Test object at 0x7fb4e855cb70>
Hello 0
####### on_message #######
<__main__.Test object at 0x7fb4e855cb70>
Hello 1
####### on_message #######
<__main__.Test object at 0x7fb4e855cb70>
Hello 2
thread terminating...
####### on_close #######
<__main__.Test object at 0x7fb4e855cb70>
####### closed #######
"""

静态方法作为 WebSocketApp 回调

缺点是回调方法中无法获得 self

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""import websocket
from websocket import WebSocketApptry:import thread
except ImportError:import _thread as thread
import timeclass Test(object):def __init__(self):super(Test, self).__init__()self.url = "ws://echo.websocket.org/"self.ws = None@staticmethoddef on_message(ws, message):print("####### on_message #######")print(ws)print(message)@staticmethoddef on_error(ws, error):print("####### on_error #######")print(ws)print(error)@staticmethoddef on_close(ws):print("####### on_close #######")print(ws)print("####### closed #######")@staticmethoddef on_open(ws):print(ws)def run(*args):for i in range(3):time.sleep(1)ws.send("Hello %d" % i)time.sleep(1)ws.close()print("thread terminating...")thread.start_new_thread(run, ())def start(self):self.ws = WebSocketApp(self.url,on_message=self.on_message,on_error=self.on_error,on_close=self.on_close)self.ws.on_open = self.on_openself.ws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)if __name__ == '__main__':Test().start()"""
<websocket._app.WebSocketApp object at 0x7f05f2a580f0>
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f05f2a580f0>
Hello 0
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f05f2a580f0>
Hello 1
####### on_message #######
<websocket._app.WebSocketApp object at 0x7f05f2a580f0>
Hello 2
####### on_close #######
<websocket._app.WebSocketApp object at 0x7f05f2a580f0>
####### closed #######
"""

子类方式

class 继承 WebSocketApp,作为其子类。但这种方法不够灵活。

# -*- coding:utf-8 -*-"""
@author:    tz_zs
"""import websocket
from websocket import WebSocketApptry:import thread
except ImportError:import _thread as thread
import timeclass Test(WebSocketApp):def __init__(self):self.url = "ws://echo.websocket.org/"super(Test, self).__init__(url=self.url, on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)def on_message(self, message):print("####### on_message #######")print(self)print(message)def on_error(self, error):print("####### on_error #######")print(self)print(error)def on_close(self):print("####### on_close #######")print(self)print("####### closed #######")def on_open(self):print(self)def run(*args):for i in range(3):time.sleep(1)self.send("Hello %d" % i)time.sleep(1)self.close()print("thread terminating...")thread.start_new_thread(run, ())# def start(self):#     ws = websocket.WebSocketApp(self.url,#                                 on_message=self.on_message,#                                 on_error=self.on_error,#                                 on_close=self.on_close)#     ws.on_open = self.on_open#     ws.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)if __name__ == '__main__':obj = Test()obj.run_forever(http_proxy_host="127.0.0.1", http_proxy_port=8118)"""
<__main__.Test object at 0x7f8a3d7e2908>
####### on_message #######
<__main__.Test object at 0x7f8a3d7e2908>
Hello 0
####### on_message #######
<__main__.Test object at 0x7f8a3d7e2908>
Hello 1
####### on_message #######
<__main__.Test object at 0x7f8a3d7e2908>
Hello 2
####### on_close #######
<__main__.Test object at 0x7f8a3d7e2908>
####### closed #######
"""

其他方法:版本回退到 0.48.0

从网站下载低版本
https://launchpad.net/ubuntu/+source/websocket-client/0.48.0-1
解压提取,使用以下命令安装
sudo python3 setup.py install

附:新老版本源码

版本 websocket-client 0.44.0

"""
websocket - WebSocket client library for PythonCopyright (C) 2010 Hiroki Ohtani(liris)This library is free software; you can redistribute it and/ormodify it under the terms of the GNU Lesser General PublicLicense as published by the Free Software Foundation; eitherversion 2.1 of the License, or (at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNULesser General Public License for more details.You should have received a copy of the GNU Lesser General PublicLicense along with this library; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin Street, Fifth Floor,Boston, MA  02110-1335  USA""""""
WebSocketApp provides higher level APIs.
"""
import select
import sys
import threading
import time
import tracebackimport sixfrom ._abnf import ABNF
from ._core import WebSocket, getdefaulttimeout
from ._exceptions import *
from . import _logging__all__ = ["WebSocketApp"]class WebSocketApp(object):"""Higher level of APIs are provided.The interface is like JavaScript WebSocket object."""def __init__(self, url, header=None,on_open=None, on_message=None, on_error=None,on_close=None, on_ping=None, on_pong=None,on_cont_message=None,keep_running=True, get_mask_key=None, cookie=None,subprotocols=None,on_data=None):"""url: websocket url.header: custom header for websocket handshake.on_open: callable object which is called at opening websocket.this function has one argument. The argument is this class object.on_message: callable object which is called when received data.on_message has 2 arguments.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.on_error: callable object which is called when we get error.on_error has 2 arguments.The 1st argument is this class object.The 2nd argument is exception object.on_close: callable object which is called when closed the connection.this function has one argument. The argument is this class object.on_cont_message: callback object which is called when receive continuedframe data.on_cont_message has 3 arguments.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.The 3rd argument is continue flag. if 0, the data continueto next frame dataon_data: callback object which is called when a message received.This is called before on_message or on_cont_message,and then on_message or on_cont_message is called.on_data has 4 argument.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.The 4th argument is continue flag. if 0, the data continuekeep_running: a boolean flag indicating whether the app's main loopshould keep running, defaults to Trueget_mask_key: a callable to produce new mask keys,see the WebSocket.set_mask_key's docstring for more informationsubprotocols: array of available sub protocols. default is None."""self.url = urlself.header = header if header is not None else []self.cookie = cookieself.on_open = on_openself.on_message = on_messageself.on_data = on_dataself.on_error = on_errorself.on_close = on_closeself.on_ping = on_pingself.on_pong = on_pongself.on_cont_message = on_cont_messageself.keep_running = keep_runningself.get_mask_key = get_mask_keyself.sock = Noneself.last_ping_tm = 0self.last_pong_tm = 0self.subprotocols = subprotocolsdef send(self, data, opcode=ABNF.OPCODE_TEXT):"""send message.data: message to send. If you set opcode to OPCODE_TEXT,data must be utf-8 string or unicode.opcode: operation code of data. default is OPCODE_TEXT."""if not self.sock or self.sock.send(data, opcode) == 0:raise WebSocketConnectionClosedException("Connection is already closed.")def close(self, **kwargs):"""close websocket connection."""self.keep_running = Falseif self.sock:self.sock.close(**kwargs)def _send_ping(self, interval, event):while not event.wait(interval):self.last_ping_tm = time.time()if self.sock:try:self.sock.ping()except Exception as ex:_logging.warning("send_ping routine terminated: {}".format(ex))breakdef run_forever(self, sockopt=None, sslopt=None,ping_interval=0, ping_timeout=None,http_proxy_host=None, http_proxy_port=None,http_no_proxy=None, http_proxy_auth=None,skip_utf8_validation=False,host=None, origin=None):"""run event loop for WebSocket framework.This loop is infinite loop and is alive during websocket is available.sockopt: values for socket.setsockopt.sockopt must be tupleand each element is argument of sock.setsockopt.sslopt: ssl socket optional dict.ping_interval: automatically send "ping" commandevery specified period(second)if set to 0, not send automatically.ping_timeout: timeout(second) if the pong message is not received.http_proxy_host: http proxy host name.http_proxy_port: http proxy port. If not set, set to 80.http_no_proxy: host names, which doesn't use proxy.skip_utf8_validation: skip utf8 validation.host: update host header.origin: update origin header."""if not ping_timeout or ping_timeout <= 0:ping_timeout = Noneif ping_timeout and ping_interval and ping_interval <= ping_timeout:raise WebSocketException("Ensure ping_interval > ping_timeout")if sockopt is None:sockopt = []if sslopt is None:sslopt = {}if self.sock:raise WebSocketException("socket is already opened")thread = Noneclose_frame = Nonetry:self.sock = WebSocket(self.get_mask_key, sockopt=sockopt, sslopt=sslopt,fire_cont_frame=self.on_cont_message and True or False,skip_utf8_validation=skip_utf8_validation)self.sock.settimeout(getdefaulttimeout())self.sock.connect(self.url, header=self.header, cookie=self.cookie,http_proxy_host=http_proxy_host,http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy,http_proxy_auth=http_proxy_auth, subprotocols=self.subprotocols,host=host, origin=origin)self._callback(self.on_open)if ping_interval:event = threading.Event()thread = threading.Thread(target=self._send_ping, args=(ping_interval, event))thread.setDaemon(True)thread.start()while self.sock.connected:r, w, e = select.select((self.sock.sock, ), (), (), ping_timeout or 10) # Use a 10 second timeout to avoid to wait forever on closeif not self.keep_running:breakif r:op_code, frame = self.sock.recv_data_frame(True)if op_code == ABNF.OPCODE_CLOSE:close_frame = framebreakelif op_code == ABNF.OPCODE_PING:self._callback(self.on_ping, frame.data)elif op_code == ABNF.OPCODE_PONG:self.last_pong_tm = time.time()self._callback(self.on_pong, frame.data)elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:self._callback(self.on_data, data,frame.opcode, frame.fin)self._callback(self.on_cont_message,frame.data, frame.fin)else:data = frame.dataif six.PY3 and op_code == ABNF.OPCODE_TEXT:data = data.decode("utf-8")self._callback(self.on_data, data, frame.opcode, True)self._callback(self.on_message, data)if ping_timeout and self.last_ping_tm \and time.time() - self.last_ping_tm > ping_timeout \and self.last_ping_tm - self.last_pong_tm > ping_timeout:raise WebSocketTimeoutException("ping/pong timed out")except (Exception, KeyboardInterrupt, SystemExit) as e:self._callback(self.on_error, e)if isinstance(e, SystemExit):# propagate SystemExit furtherraisefinally:if thread and thread.isAlive():event.set()thread.join()self.keep_running = Falseself.sock.close()close_args = self._get_close_args(close_frame.data if close_frame else None)self._callback(self.on_close, *close_args)self.sock = Nonedef _get_close_args(self, data):""" this functions extracts the code, reason from the close bodyif they exists, and if the self.on_close except three arguments """import inspect# if the on_close callback is "old", just return empty listif sys.version_info < (3, 0):if not self.on_close or len(inspect.getargspec(self.on_close).args) != 3:return []else:if not self.on_close or len(inspect.getfullargspec(self.on_close).args) != 3:return []if data and len(data) >= 2:code = 256 * six.byte2int(data[0:1]) + six.byte2int(data[1:2])reason = data[2:].decode('utf-8')return [code, reason]return [None, None]def _callback(self, callback, *args):if callback:try:callback(self, *args)except Exception as e:_logging.error("error from callback {}: {}".format(callback, e))if _logging.isEnabledForDebug():_, _, tb = sys.exc_info()traceback.print_tb(tb)

版本 websocket-client 0.56.0

"""
websocket - WebSocket client library for PythonCopyright (C) 2010 Hiroki Ohtani(liris)This library is free software; you can redistribute it and/ormodify it under the terms of the GNU Lesser General PublicLicense as published by the Free Software Foundation; eitherversion 2.1 of the License, or (at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNULesser General Public License for more details.You should have received a copy of the GNU Lesser General PublicLicense along with this library; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin Street, Fifth Floor,Boston, MA  02110-1335  USA""""""
WebSocketApp provides higher level APIs.
"""
import inspect
import select
import sys
import threading
import time
import tracebackimport sixfrom ._abnf import ABNF
from ._core import WebSocket, getdefaulttimeout
from ._exceptions import *
from . import _logging__all__ = ["WebSocketApp"]class Dispatcher:def __init__(self, app, ping_timeout):self.app  = appself.ping_timeout = ping_timeoutdef read(self, sock, read_callback, check_callback):while self.app.sock.connected:r, w, e = select.select((self.app.sock.sock, ), (), (), self.ping_timeout)if r:if not read_callback():breakcheck_callback()class SSLDispacther:def __init__(self, app, ping_timeout):self.app  = appself.ping_timeout = ping_timeoutdef read(self, sock, read_callback, check_callback):while self.app.sock.connected:r = self.select()if r:if not read_callback():breakcheck_callback()def select(self):sock = self.app.sock.sockif sock.pending():return [sock,]r, w, e = select.select((sock, ), (), (), self.ping_timeout)return rclass WebSocketApp(object):"""Higher level of APIs are provided.The interface is like JavaScript WebSocket object."""def __init__(self, url, header=None,on_open=None, on_message=None, on_error=None,on_close=None, on_ping=None, on_pong=None,on_cont_message=None,keep_running=True, get_mask_key=None, cookie=None,subprotocols=None,on_data=None):"""url: websocket url.header: custom header for websocket handshake.on_open: callable object which is called at opening websocket.this function has one argument. The argument is this class object.on_message: callable object which is called when received data.on_message has 2 arguments.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.on_error: callable object which is called when we get error.on_error has 2 arguments.The 1st argument is this class object.The 2nd argument is exception object.on_close: callable object which is called when closed the connection.this function has one argument. The argument is this class object.on_cont_message: callback object which is called when receive continuedframe data.on_cont_message has 3 arguments.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.The 3rd argument is continue flag. if 0, the data continueto next frame dataon_data: callback object which is called when a message received.This is called before on_message or on_cont_message,and then on_message or on_cont_message is called.on_data has 4 argument.The 1st argument is this class object.The 2nd argument is utf-8 string which we get from the server.The 3rd argument is data type. ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY will be came.The 4th argument is continue flag. if 0, the data continuekeep_running: this parameter is obsolete and ignored.get_mask_key: a callable to produce new mask keys,see the WebSocket.set_mask_key's docstring for more informationsubprotocols: array of available sub protocols. default is None."""self.url = urlself.header = header if header is not None else []self.cookie = cookieself.on_open = on_openself.on_message = on_messageself.on_data = on_dataself.on_error = on_errorself.on_close = on_closeself.on_ping = on_pingself.on_pong = on_pongself.on_cont_message = on_cont_messageself.keep_running = Falseself.get_mask_key = get_mask_keyself.sock = Noneself.last_ping_tm = 0self.last_pong_tm = 0self.subprotocols = subprotocolsdef send(self, data, opcode=ABNF.OPCODE_TEXT):"""send message.data: message to send. If you set opcode to OPCODE_TEXT,data must be utf-8 string or unicode.opcode: operation code of data. default is OPCODE_TEXT."""if not self.sock or self.sock.send(data, opcode) == 0:raise WebSocketConnectionClosedException("Connection is already closed.")def close(self, **kwargs):"""close websocket connection."""self.keep_running = Falseif self.sock:self.sock.close(**kwargs)self.sock = Nonedef _send_ping(self, interval, event):while not event.wait(interval):self.last_ping_tm = time.time()if self.sock:try:self.sock.ping()except Exception as ex:_logging.warning("send_ping routine terminated: {}".format(ex))breakdef run_forever(self, sockopt=None, sslopt=None,ping_interval=0, ping_timeout=None,http_proxy_host=None, http_proxy_port=None,http_no_proxy=None, http_proxy_auth=None,skip_utf8_validation=False,host=None, origin=None, dispatcher=None,suppress_origin = False, proxy_type=None):"""run event loop for WebSocket framework.This loop is infinite loop and is alive during websocket is available.sockopt: values for socket.setsockopt.sockopt must be tupleand each element is argument of sock.setsockopt.sslopt: ssl socket optional dict.ping_interval: automatically send "ping" commandevery specified period(second)if set to 0, not send automatically.ping_timeout: timeout(second) if the pong message is not received.http_proxy_host: http proxy host name.http_proxy_port: http proxy port. If not set, set to 80.http_no_proxy: host names, which doesn't use proxy.skip_utf8_validation: skip utf8 validation.host: update host header.origin: update origin header.dispatcher: customize reading data from socket.suppress_origin: suppress outputting origin header.Returns-------False if caught KeyboardInterruptTrue if other exception was raised during a loop"""if ping_timeout is not None and ping_timeout <= 0:ping_timeout = Noneif ping_timeout and ping_interval and ping_interval <= ping_timeout:raise WebSocketException("Ensure ping_interval > ping_timeout")if not sockopt:sockopt = []if not sslopt:sslopt = {}if self.sock:raise WebSocketException("socket is already opened")thread = Noneself.keep_running = Trueself.last_ping_tm = 0self.last_pong_tm = 0def teardown(close_frame=None):"""Tears down the connection.If close_frame is set, we will invoke the on_close handler with thestatusCode and reason from there."""if thread and thread.isAlive():event.set()thread.join()self.keep_running = Falseif self.sock:self.sock.close()close_args = self._get_close_args(close_frame.data if close_frame else None)self._callback(self.on_close, *close_args)self.sock = Nonetry:self.sock = WebSocket(self.get_mask_key, sockopt=sockopt, sslopt=sslopt,fire_cont_frame=self.on_cont_message is not None,skip_utf8_validation=skip_utf8_validation,enable_multithread=True if ping_interval else False)self.sock.settimeout(getdefaulttimeout())self.sock.connect(self.url, header=self.header, cookie=self.cookie,http_proxy_host=http_proxy_host,http_proxy_port=http_proxy_port, http_no_proxy=http_no_proxy,http_proxy_auth=http_proxy_auth, subprotocols=self.subprotocols,host=host, origin=origin, suppress_origin=suppress_origin,proxy_type=proxy_type)if not dispatcher:dispatcher = self.create_dispatcher(ping_timeout)self._callback(self.on_open)if ping_interval:event = threading.Event()thread = threading.Thread(target=self._send_ping, args=(ping_interval, event))thread.setDaemon(True)thread.start()def read():if not self.keep_running:return teardown()op_code, frame = self.sock.recv_data_frame(True)if op_code == ABNF.OPCODE_CLOSE:return teardown(frame)elif op_code == ABNF.OPCODE_PING:self._callback(self.on_ping, frame.data)elif op_code == ABNF.OPCODE_PONG:self.last_pong_tm = time.time()self._callback(self.on_pong, frame.data)elif op_code == ABNF.OPCODE_CONT and self.on_cont_message:self._callback(self.on_data, frame.data,frame.opcode, frame.fin)self._callback(self.on_cont_message,frame.data, frame.fin)else:data = frame.dataif six.PY3 and op_code == ABNF.OPCODE_TEXT:data = data.decode("utf-8")self._callback(self.on_data, data, frame.opcode, True)self._callback(self.on_message, data)return Truedef check():if (ping_timeout):has_timeout_expired = time.time() - self.last_ping_tm > ping_timeouthas_pong_not_arrived_after_last_ping = self.last_pong_tm - self.last_ping_tm < 0has_pong_arrived_too_late = self.last_pong_tm - self.last_ping_tm > ping_timeoutif (self.last_ping_tmand has_timeout_expiredand (has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late)):raise WebSocketTimeoutException("ping/pong timed out")return Truedispatcher.read(self.sock.sock, read, check)except (Exception, KeyboardInterrupt, SystemExit) as e:self._callback(self.on_error, e)if isinstance(e, SystemExit):# propagate SystemExit furtherraiseteardown()return not isinstance(e, KeyboardInterrupt)def create_dispatcher(self, ping_timeout):timeout = ping_timeout or 10if self.sock.is_ssl():return SSLDispacther(self, timeout)return Dispatcher(self, timeout)def _get_close_args(self, data):""" this functions extracts the code, reason from the close bodyif they exists, and if the self.on_close except three arguments """# if the on_close callback is "old", just return empty listif sys.version_info < (3, 0):if not self.on_close or len(inspect.getargspec(self.on_close).args) != 3:return []else:if not self.on_close or len(inspect.getfullargspec(self.on_close).args) != 3:return []if data and len(data) >= 2:code = 256 * six.byte2int(data[0:1]) + six.byte2int(data[1:2])reason = data[2:].decode('utf-8')return [code, reason]return [None, None]def _callback(self, callback, *args):if callback:try:if inspect.ismethod(callback):callback(*args)else:callback(self, *args)except Exception as e:_logging.error("error from callback {}: {}".format(callback, e))if _logging.isEnabledForDebug():_, _, tb = sys.exc_info()traceback.print_tb(tb)

相关讨论

https://stackoverflow.com/questions/26980966/using-a-websocket-client-as-a-class-in-python
Passing method of non-WebSocketApp object as callback does not receive the WebSocketApp object as an argument
why the function “WebSocketApp run_forever” doesn’t work in linux? But it’s OK in windows.

这篇关于Python websocket 模块 WebSocketApp 长连接方法新老版本不兼容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/954314

相关文章

Django开发时如何避免频繁发送短信验证码(python图文代码)

《Django开发时如何避免频繁发送短信验证码(python图文代码)》Django开发时,为防止频繁发送验证码,后端需用Redis限制请求频率,结合管道技术提升效率,通过生产者消费者模式解耦业务逻辑... 目录避免频繁发送 验证码1. www.chinasem.cn避免频繁发送 验证码逻辑分析2. 避免频繁

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

Python标准库之数据压缩和存档的应用详解

《Python标准库之数据压缩和存档的应用详解》在数据处理与存储领域,压缩和存档是提升效率的关键技术,Python标准库提供了一套完整的工具链,下面小编就来和大家简单介绍一下吧... 目录一、核心模块架构与设计哲学二、关键模块深度解析1.tarfile:专业级归档工具2.zipfile:跨平台归档首选3.

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3