Snippets

zhuang zhuang HookSocketIO

Created by zhuang zhuang
import socket
from contextlib import contextmanager
import requests
from socket import SocketIO as _SocketIO


@contextmanager
def hook_socket_context():
    buffer = []

    class SocketIO(_SocketIO):
        def readinto(self, b):
            print('hooking')
            res = super().readinto(b)
            if res > 0:
                buffer.append(bytes(b[:res]))
            return res
    socket.SocketIO = SocketIO
    yield buffer
    socket.SocketIO = _SocketIO


with hook_socket_context() as buf:
    requests.get('https://v2ex.com/t/607316#reply10')
    print(b''.join(buf))

print('with out hook')
requests.get('https://v2ex.com/t/607316#reply10')
print('done!')

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.