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)
相关推荐
我是一颗柠檬16 小时前
【计算机网络全面教学】网络层与IP协议,子网划分到路由协议全掌握Day3(2026年)
网络协议·tcp/ip·计算机网络
meilindehuzi_a16 小时前
深入理解 Ajax 异步请求:从 XMLHttpRequest 到 Node.js HTTP 服务实践
http·ajax·node.js
阿米亚波16 小时前
SSH+TCP流程及抓包说明
网络·笔记·网络协议·tcp/ip·计算机网络·wireshark·ssh
艾莉丝努力练剑17 小时前
【Qt】界面优化:绘图API
linux·运维·开发语言·网络·qt·tcp/ip·udp
伶俜6617 小时前
鸿蒙原生应用实战(九)ArkUI 天气预报 App:HTTP 请求 + 定位 + 动效
http·华为·harmonyos
BlockWay17 小时前
WEEX WebSocket 与 API 生态,正在解决什么问题?
网络·websocket·网络协议
我是一颗柠檬17 小时前
【计算机网络全面教学】传输层TCP与UDP,三次握手到拥塞控制彻底搞懂Day4(2026年)
tcp/ip·计算机网络·udp
逻极17 小时前
HTTP/HTTPS 协议从入门到精通:从原理到性能提升400%的完整路径(协议优化实战)
网络协议·http·性能优化·https·tls
芒鸽17 小时前
HarmonyOS 网络编程实战:HTTP、WebSocket 与 Socket 通信详解
网络·http·harmonyos
努力的lpp17 小时前
渗透主流工具完整参数手册(sqlmap、Nmap、Hydra、Dirsearch、Xray)
javascript·网络协议·测试工具·安全·http·工具