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)
相关推荐
小新讲网安18 小时前
HTTP请求走私攻击实战:CL.TE与TE.CL绕过前端服务器全解析
服务器·前端·网络·web安全·http·架构·漏洞
wear工程师1 天前
接口超时别只调大 timeout:Java HTTP 客户端其实有 3 段等待
java·http
蜡台1 天前
本机 局域网 搭建本地 HTTPS 域名完整方案
网络协议·http·https·openssl
云老大-阿里云国际站代理商2 天前
腾讯云国际站代理商:CVM 跨地域网络抖动排查,深度分析 TCP 重传与 MTU 问题
网络·tcp/ip·腾讯云
k4m7v2pz2 天前
Rust 高并发 WebSocket 连接管理:从线程地狱到 tokio 异步架构
websocket·架构·rust·并发编程·tokio
IpdataCloud2 天前
IPv6查出来的地理位置是错的?技术解析与双栈定位方案
数据库·tcp/ip·ip
Alkaid20772 天前
为什么查 IP 有两个结果?这个问题问倒过多少人
网络协议·tcp/ip
ly76892 天前
计算机网络:从分层模型到 TCP/IP、HTTP 与网络排查
网络·tcp/ip·计算机网络
海拥✘2 天前
Python 实战:用 IPPEAK 代理 IP 构建稳定的公开数据采集链路
网络·python·tcp/ip
ControlRookie2 天前
第13篇_Client 02|TCP 连接成功,为什么 HTTP 请求还没有成功
http·codesys·plc通信·controlrookie