wuxiaolin
V2EX  ›  Python

关于 threading 连接多个 websocket 服务之后出现的疑问

By wuxiaolin at 2023 年 2 月 1 日 · 2330 次点击

首先描述问题,通过 threading 去连接多个 websocket 服务,服务是都连接成功了。但是代码执行到“ws = WebSocketHandler(self.host, self.name)”之后就不执行了,初次接触,没找到原因,还请熟悉 python 的朋友给传授下经验

class ThreadingHandler(threading.Thread):
    host = ''
    name = ''
    q = ''

    def __init__(self, host, name, queue):
        '''
        重写父类 init
        :param host: 服务器地址
        :param name: 服务器名称
        '''

        super().__init__()

        self.host = host
        self.name = name
        self.q = queue

    def run(self):
        ws = WebSocketHandler(self.host, self.name)
		
        # 这里往后就没在执行了
        print(ws)

class WebSocketHandler():
    """
    socket handler
    """

    # websocket 服务地址
    host = ''

    # 服务器名称
    name = ''

    # websocket 实例
    socketInstance = ''

    # 服务链接状态
    connectStatus = False

    def __init__(self, host, name):
        '''
        :param host:服务器地址
        :param name:服务器名称
        :return
        '''

        self.host = host
        self.name = name

        # 连接服务器
        self.connect()

        return self.socketInstance

    def connect(self):
        '''
        链接服务器
        '''

        # debug 模式
        # websocket.enableTrace(True)

        self.socketInstance = websocket.WebSocketApp(
            self.host, 
            on_open = self.onOpen,
            on_message = self.onMessage,
            on_error = self.onError,
            on_close = self.onClose
        )

        self.socketInstance.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
2 条回复  •  2023-02-02 10:13:49 +08:00
learningman
   1
learningman  
   2023 年 2 月 1 日
__init__ 里执行了个叫 run_forever 的函数,block 不是很正常
wuxiaolin
   2
wuxiaolin  
OP
   2023 年 2 月 2 日
@learningman 感谢解答
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
© 2026 V2EX · 25ms · 3.9.8.5