我是靠谱客的博主 无情水壶,最近开发中收集的这篇文章主要介绍Python websocket模块 ping/pong控制帧及日志的开启,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

____tz_zs

websocket-client 版本 0.57.0

(一)on_open

调用 run_forever 建立连接时,websocket 模块会先 源码 websocket/_app.py > 259 行 > self._callback(self.on_open) 函数 通知 on_open 回调函数,连接建立。

(二)on_ping、on_pong

服务器发送 ping帧 过来时,websocket 模块会调用 源码 websocket/_app.py > 276 行 > self._callback(self.on_ping, frame.data) 函数 回调 on_ping 回调函数。

当你发送 ping帧 到服务器时,例如使用 self._ws_client.send("my_ping", ABNF.OPCODE_PING) 发送 “my_ping”;服务器会返回 pong帧,此时 websocket 模块会调用 源码 websocket/_app.py > 278 279 行 > self.last_pong_tm = time.time() 和 self._callback(self.on_pong, frame.data) 回调 on_pong 回调函数,你将得到 bytes 类型消息 b'my_ping'

websocket/_app.py run_forever函数的部分源码

... ...
... ...
            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.data
                    if 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 True
... ...
... ...

websocket/_app.py _callback函数的部分源码

    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)

(三)ws_client.send()

websocket 模块中用于发送消息的 send 函数 send(self, data, opcode=ABNF.OPCODE_TEXT) 有两个参数,第一个参数 data 为发送到数据,第二个参数 opcode 传入控制帧,默认参数为文本数据帧。

OPCODE_CONT = 0x0 表示附加数据帧
OPCODE_TEXT = 0x1 表示文本数据帧
OPCODE_BINARY = 0x2 表示二进制数据帧
OPCODE_CLOSE = 0x8 表示连接关闭
OPCODE_PING = 0x9 表示ping
OPCODE_PONG = 0xa 表示pong

websocket/_app.py send函数的部分源码

    def 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.")

websocket/_abnf.py ABNF类的部分源码

... ...
... ...
    # operation code values.
    OPCODE_CONT = 0x0
    OPCODE_TEXT = 0x1
    OPCODE_BINARY = 0x2
    OPCODE_CLOSE = 0x8
    OPCODE_PING = 0x9
    OPCODE_PONG = 0xa
... ...
... ...

(四)logger 开启日志

websocket 模块的日志模块 _logging.py 默认是添加的空的 headler (源码 websocket/_logging.py > 32 行 > _logger.addHandler(NullHandler())),且追踪默认是关闭状态 (源码 websocket/_logging.py > 34 行 > _traceEnabled = False),所以我们在调试时,看不到 websocket 模块中的日志报错。
这样不方便调试和优化代码,我们可以通过 websocket.enableTrace(True) 启用日志记录输出,他会添加一个 StreamHandler 且将_traceEnabled 置为 True。

websocket/_logging.py 源码

"""
websocket - WebSocket client library for Python

Copyright (C) 2010 Hiroki Ohtani(liris)

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 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 of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA  02110-1335  USA

"""
import logging

_logger = logging.getLogger('websocket')
try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

_logger.addHandler(NullHandler())

_traceEnabled = False

__all__ = ["enableTrace", "dump", "error", "warning", "debug", "trace",
           "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace"]


def enableTrace(traceable, handler = logging.StreamHandler()):
    """
    turn on/off the traceability.

    traceable: boolean value. if set True, traceability is enabled.
    """
    global _traceEnabled
    _traceEnabled = traceable
    if traceable:
        _logger.addHandler(handler)
        _logger.setLevel(logging.DEBUG)

def dump(title, message):
    if _traceEnabled:
        _logger.debug("--- " + title + " ---")
        _logger.debug(message)
        _logger.debug("-----------------------")


def error(msg):
    _logger.error(msg)


def warning(msg):
    _logger.warning(msg)


def debug(msg):
    _logger.debug(msg)


def trace(msg):
    if _traceEnabled:
        _logger.debug(msg)


def isEnabledForError():
    return _logger.isEnabledFor(logging.ERROR)


def isEnabledForDebug():
    return _logger.isEnabledFor(logging.DEBUG)

def isEnabledForTrace():
    return _traceEnabled

最后

以上就是无情水壶为你收集整理的Python websocket模块 ping/pong控制帧及日志的开启的全部内容,希望文章能够帮你解决Python websocket模块 ping/pong控制帧及日志的开启所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部