一个简单的websocket服务

参考: https://pypi.org/project/websockets/

python 复制代码
#!/usr/bin/env python3
import asyncio
from websockets.server import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "127.0.0.1", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

获取ip的方法

python 复制代码
def getIp(websocket):
    header = websocket.request_headers
    remote_host = header.get(REMOTE_HOST_KEY)
    if remote_host is not None:
        return remote_host
    return websocket.remote_address[0]

nginx配置

复制代码
location /asyncio {
    add_header Access-Control-Allow-Origin *;
    proxy_pass http://127.0.0.1:8765$request_uri;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header REMOTE-HOST $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

如果机器上有stl证书,上面这样配置,访问 wss://${域名}/asyncio 即可访问到上面部署的echo服务。

相关推荐
IPdodo_3 小时前
跨境 API 调用不稳定怎么办:出口、超时重试与链路监控的实践
网络·python·网络协议
xiaoye-duck6 小时前
《Linux 网络编程》深入理解 IP 协议(二):网段划分、私有 IP 与 NAT 地址转换
linux·网络·ip
广州宏帝箱包9 小时前
出口箱包的包装标准:防潮、防摔、运输安全的设计要点
大数据·网络
彧azz9 小时前
Linux 网络编程学习总结
linux·网络·笔记·学习·面试
updayday85410 小时前
离职域账号状态变更与Ping64操作记录核对
大数据·网络·数据库·安全·智能路由器
安易算力10 小时前
PUE优化工程实践:从1.5到1.2的制冷架构与气流组织改造路径
网络·python·容器·架构·kubernetes
Ivanqhz11 小时前
数据搬运是性能关键
java·服务器·网络·人工智能·深度学习
Julien200412 小时前
自动挂载网络附加存储
linux·服务器·网络
K成长日志12 小时前
BLE链路层-隐私保护
网络·物联网·蓝牙·iot·ble