Python3使用websocket调用http代理IP

1、安装

bash 复制代码
pip install websocket-client

2、运行环境要求

此代码需要运行在 Python 3.x 环境中,确保你的 Python 版本符合要求。

3、示例代码

python 复制代码
import gzip
import zlib
import websocket

OPCODE_DATA = (websocket.ABNF.OPCODE_TEXT, websocket.ABNF.OPCODE_BINARY)
url = "ws://echo.websocket.events/"
proxies = {
    "http_proxy_host": "168.38.24.125",
    "http_proxy_port": 16898,
    "http_proxy_auth": ("username", "password"),
}
ws = websocket.create_connection(url, **proxies)

def recv():
    try:
        frame = ws.recv_frame()
    except websocket.WebSocketException:
        return websocket.ABNF.OPCODE_CLOSE, None
    if not frame:
        raise websocket.WebSocketException("Not a valid frame {}".format(frame))
    elif frame.opcode in OPCODE_DATA:
        return frame.opcode, frame.data
    elif frame.opcode == websocket.ABNF.OPCODE_CLOSE:
        ws.send_close()
        return frame.opcode, None
    elif frame.opcode == websocket.ABNF.OPCODE_PING:
        ws.pong(frame.data)
        return frame.opcode, frame.data

    return frame.opcode, frame.data

def recv_ws():
    opcode, data = recv()
    if opcode == websocket.ABNF.OPCODE_CLOSE:
        return
    if opcode == websocket.ABNF.OPCODE_TEXT and isinstance(data, bytes):
        data = str(data, "utf-8")
    if isinstance(data, bytes) and len(data) > 2 and data[:2] == b'\037\213':  # gzip magic
        try:
            data = "[gzip] {}".format(str(gzip.decompress(data), "utf-8"))
        except Exception:
            pass
    elif isinstance(data, bytes):
        try:
            data = "[zlib] {}".format(str(zlib.decompress(data, -zlib.MAX_WBITS), "utf-8"))
        except Exception:
            pass
    if isinstance(data, bytes):
        data = repr(data)

    print("< {}".format(data))

def main():
    print("Press Ctrl+C to quit")
    while True:
        message = input("> ")
        ws.send(message)
        recv_ws()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print('\nbye')
    except Exception as e:
        print(e)
相关推荐
夜雪一千2 小时前
TCP协议简介
网络·网络协议·tcp/ip
TlSfoward2 小时前
如何用 TLS 与 HTTP 指标降低误伤 TLSFOWARD抓包工具
网络·网络协议·http
沐苏瑶6 小时前
计算机网络核心笔记:打通 TCP/UDP 与 HTTP/HTTPS 底层逻辑(重点上)
笔记·计算机网络·http·https
会编程的土豆6 小时前
HTTP 是什么:你打开 localhost:8080 时发生了什么
网络·网络协议·http
M1582276905515 小时前
跨协议互通利器|SG-PN-EIP (S)-220 Profinet 转 EtherNet/IP 网关,打通欧美 PLC 通讯壁垒
网络·网络协议·tcp/ip
闲猫17 小时前
Spring AI对接Deepseek 使用Charles代理api.deepseek.com 拦截报文,查看Tool和Skill的本质
网络·网络协议·http
跨境技工小黎21 小时前
2026如何解决Cloudflare 5秒盾/无限验证码问题?
tcp/ip
华翔天诚科技1 天前
基于 CK-PR09-TCP 高精度 RFID定位的龙门式行车精准停靠方案(对标低频普通 RFID定位升级方案)
网络·网络协议·tcp/ip
Tongzhi20261 天前
上海通芝半球型无感识别摄像机 vs 传统考勤终端 vs 普通IP摄像机:品类边界、规格实测与成本账本
网络·网络协议·tcp/ip