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)
相关推荐
pengyi87101529 分钟前
共享 IP 防封维护策略,降低被封率、延长 IP 寿命
网络·网络协议·tcp/ip
wu@555551 小时前
使用acme生成免费https泛域名证书(通配符证书)
网络协议·http·https
Bat U2 小时前
JavaEE|网络原理TCP/IP
网络·网络协议·tcp/ip
不是山谷.:.2 小时前
前端零基础入门:WebSocket 全解析
前端·笔记·websocket·状态模式
wljt2 小时前
为什么要使用Spring Cloud,而不是HTTP直接调用接口?
spring·http·spring cloud
HMS工业网络2 小时前
Cosy通过USB连接PLC时如何排查USB over IP故障
网络·网络协议·tcp/ip
小船跨境2 小时前
如何验证代理IP纯净度?2026年IP检测与优化指南
网络·网络协议·tcp/ip
minji...3 小时前
Linux 网络基础之网络IP层(十)IP 协议,网段划分,IP地址相关问题
linux·运维·服务器·网络·tcp/ip·智能路由器·php
lolo大魔王3 小时前
Go 语言 HTTP 协议与 RESTful API 实训全解(理论 + 实战 + 规范)
http·golang·restful
念越3 小时前
UDP 与 TCP 协议详解
网络协议·tcp/ip·udp·tcp