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)
相关推荐
codeejun5 小时前
每日一Go-44、Go网络栈深度拆解--从 TCP 到 HTTP 的资源复用艺术
网络·tcp/ip·golang
The_Ticker6 小时前
印度股票实时行情API(低成本方案)
python·websocket·算法·金融·区块链
上海云盾-小余7 小时前
精准抵御流量攻击:高防 IP + 游戏盾组合部署实战详解
网络·tcp/ip·游戏
okiseethenwhat7 小时前
TCP拥塞控制算法原理详解
tcp/ip
江畔何人初7 小时前
TCP的三次握手与四次挥手
linux·服务器·网络·网络协议·tcp/ip
m0_738120727 小时前
网络安全编程——Python编写基于UDP的主机发现工具(解码IP header)
python·网络协议·tcp/ip·安全·web安全·udp
liweiweili1268 小时前
http数据传输过程数据编码解码问答
网络协议·http·状态模式
有代理ip8 小时前
动态IP的安全性优化:策略升级与隐私保护实战指南
网络·网络协议·tcp/ip
CDN3608 小时前
高防 IP 回源 502/504 异常?源站放行与健康检查修复
网络·网络协议·tcp/ip
fqq39 小时前
Http方法详解
网络·网络协议·http