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 小时前
HTTP 协议的基本格式
java·网络协议·http
AIwenIPgeolocation4 小时前
IP地址数据服务:赋能游戏行业体验优化与精细化运营
网络协议·tcp/ip·游戏
TechWayfarer4 小时前
2026年IP归属地查询平台选型指南:金融风控、异地登录、离线库全场景实测
网络·网络协议·tcp/ip
Rust研习社5 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust
2401_873479406 小时前
深度解析IP查询工具与普通IP库的核心区别:选型指南与业务场景对照
网络协议·tcp/ip·php
垦利不6 小时前
websocket通信
网络·websocket·网络协议
RunningBComeOn6 小时前
为什么无法抓取到http之间的明文传输
网络·网络协议·http
li星野7 小时前
FastAPI 项目加入 WebSocket 支持
python·websocket·fastapi
lbb 小魔仙7 小时前
2026远程办公软件夏季深度横测:ToDesk、向日葵、网易UU远程全面对比,远控白皮书
android·服务器·网络协议·tcp/ip·postgresql