如何自定义一个符合 IProtocol 接口的协议类来处理非标准 TCP 协议?

解读

面试官抛出这道题,核心想验证三件事:

  1. 你是否真的“手写”过 Twisted 协议,而不是只会调库;
  2. 对 IProtocol 四个钩子(connectionMade、dataReceived、connectionLost、makeConnection)的生命周期是否理解到位;
  3. 能否把“非标准 TCP 协议”常见的粘包/半包、心跳、异常恢复等问题,在 Twisted 的异步模型里优雅落地。
    国内大厂(如抖音直播网关、小米 IoT 平台)用 Twisted 做长连接接入层时,最怕候选人“理论上懂”,一上机器就写出阻塞式解析或内存暴涨的代码。因此,现场面经常让你“5 分钟白板写一段能跑的结构”,再追问性能与异常场景。

知识点

  1. IProtocol 接口四大方法签名与执行时机

    • makeConnection(transport):最先被框架回调,拿到 transport 句柄,可在这里做连接级参数调优(TCP_NODELAY、SO_KEEPALIVE、内存上限)。
    • connectionMade():TCP 三次握手完成,可下发初始化指令或开始心跳定时器。
    • dataReceived(data):每次 reactor 读就绪后被调用,data 长度不固定,需要把“流式字节流”解析成“业务消息”。
    • connectionLost(reason):对端 FIN 或 RST 触发,需清理资源、注销定时器、上报 metrics。
  2. 非标准协议常见套路

    • 固定头+变长体:头 4 字节 magic(0xFEED)+2 字节 length,先收够 6 字节再按 length 收体。
    • 心跳双工:客户端发 PING(0x09),服务端回 PONG(0x0A),连续 3 次无应答即主动 close。
    • 状态机:用自增状态常量(WAIT_MAGIC、WAIT_LEN、WAIT_BODY)避免嵌套 if。
  3. Twisted 异步资源管理

    • 用 self.transport.setTcpKeepAlive(1) 保活,比应用层心跳更省带宽。
    • 用 reactor.callLater 做超时器,返回句柄存 self._heartbeat_call,connectionLost 里一定要 cancel(),防止“已关闭连接仍触发回调”导致 AlreadyCalled 异常。
    • 大文件流控:解析到完整消息后,若业务处理慢,先 self.transport.pauseProducing(),待业务队列 < 阈值再 resumeProducing(),防止 OOM。
  4. 单元测试

    • Trial 框架里可以用 StringTransport 把协议“跑在内存”,配合 clock = task.Clock() 模拟 30 s 心跳,毫秒级完成用例。
    • 断言点:半包场景、超时不回包主动断开、异常字节流直接丢弃并关闭连接。

答案

from twisted.internet import protocol, reactor
from twisted.internet.protocol import Protocol
from twisted.internet.error import ConnectionDone
import struct
import logging

logging.basicConfig(level=logging.INFO)

class MyCustomProtocol(Protocol):
    # 协议常量
    MAGIC = 0xFEED
    HEADER_SIZE = 6          # magic(2) + length(2) + reserved(2)
    MAX_BODY = 1 * 1024 * 1024   # 1M 防护

    def __init__(self):
        self._buffer = b''
        self._expected = self.HEADER_SIZE
        self._heartbeat_call = None
        self._missed_pongs = 0
        self._transport = None          # makeConnection 里再赋值

    # ---------- IProtocol 接口实现 ----------
    def makeConnection(self, transport):
        # 先调父类,把 transport 存下来
        super().makeConnection(transport)
        self._transport = transport
        transport.setTcpNoDelay(True)
        transport.setTcpKeepAlive(True)
        logging.info("makeConnection %s", transport.getPeer())

    def connectionMade(self):
        # 握手成功后立即下发一条“HELLO”命令,并启动心跳
        self.send_message(0x01, b'HELLO')
        self._schedule_heartbeat()

    def dataReceived(self, data):
        self._buffer += data
        while len(self._buffer) >= self._expected:
            if self._expected == self.HEADER_SIZE:
                # 尝试解析头
                magic, body_len, reserved = struct.unpack('!HHH', self._buffer[:self.HEADER_SIZE])
                if magic != self.MAGIC:
                    logging.warning("Bad magic %04X, drop connection", magic)
                    self.transport.loseConnection()
                    return
                if body_len > self.MAX_BODY:
                    logging.warning("Body too large %s", body_len)
                    self.transport.loseConnection()
                    return
                self._expected = body_len
                self._buffer = self._buffer[self.HEADER_SIZE:]
            else:
                # 收 body
                body = self._buffer[:self._expected]
                self._buffer = self._buffer[self._expected:]
                self._on_message(body)
                self._expected = self.HEADER_SIZE   # 回到等头状态

    def connectionLost(self, reason):
        if self._heartbeat_call and self._heartbeat_call.active():
            self._heartbeat_call.cancel()
        logging.info("connectionLost %s", reason.value)

    # ---------- 业务层 ----------
    def _on_message(self, body):
        cmd = body[0]
        payload = body[1:]
        if cmd == 0x09:          # PING
            self.send_message(0x0A, b'PONG')
        elif cmd == 0x0A:        # PONG
            self._missed_pongs = 0
        else:
            # 交给上层 Factory 做路由
            self.factory.handle_command(self, cmd, payload)

    def send_message(self, cmd, payload):
        header = struct.pack('!HHH', self.MAGIC, len(payload) + 1, 0)
        self.transport.write(header + bytes([cmd]) + payload)

    def _schedule_heartbeat(self):
        self._heartbeat_call = reactor.callLater(30, self._send_ping)

    def _send_ping(self):
        self.send_message(0x09, b'')
        self._missed_pongs += 1
        if self._missed_pongs >= 3:
            logging.warning("Heartbeat timeout, close")
            self.transport.loseConnection()
        else:
            self._schedule_heartbeat()


class MyFactory(protocol.ServerFactory):
    protocol = MyCustomProtocol

    def handle_command(self, proto, cmd, payload):
        # 简单 echo
        proto.send_message(cmd, payload)


if __name__ == '__main__':
    reactor.listenTCP(8007, MyFactory())
    reactor.run()

代码要点

  1. 严格按 IProtocol 四大方法占位,确保 Twisted 调度器能正确回调。
  2. 用 _buffer 与 _expected 做状态机,解决粘包/半包。
  3. 心跳逻辑放在应用层,配合 TCP KeepAlive 双保险;超时计数器在 connectionLost 里清理,防止 AlreadyCalled。
  4. 通过 Factory 暴露 handle_command,方便后续把协议解析与业务逻辑解耦,也利于 Trial 写单元测试时 mock。

拓展思考

  1. 性能再进阶:如果单核跑满 50k 长连接,CPU 主要花在 dataReceived 的内存拷贝。可以把 _buffer 换成 bytearray + memoryview,收到新数据时只 extend 一次,解析完用 del self._buffer[:consumed] 原地释放,减少 realloc。
  2. 多协议复用端口:利用 Twisted 的 PrefixLineReceiver 或 twisted.protocols.policies.ProtocolSwitchingWrapper,在收到特定 magic 后再动态切换到 MyCustomProtocol,实现“一个端口兼容私有二进制+文本 HTTP”。
  3. 安全加固:国内等保 2.0 要求“长连接必须做双向认证”。可在 makeConnection 里把 transport 强转成 twisted.internet.ssl.Transport,然后 getPeerCertificate() 做校验,失败直接 loseConnection()。
  4. 灰度观测:给协议类加 prometheus_client.Counter,在 dataReceived 与 send_message 处埋点,配合 Grafana 看“解析异常关闭率”“心跳超时率”,方便 SRE 灰度发布。