一个简单的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服务。

相关推荐
想你依然心痛12 小时前
RT-Thread组件生态:SAL网络框架与AT组件实战——网络抽象、AT指令
网络·arm开发·at·sal
2401_8415851812 小时前
防破 · 稳定 · 易用——文心云网络验证,为您的软件商业化保驾护航
网络
星恒讯工业路由器12 小时前
公网IP、NAT、端口映射:外网访问家里的“通关攻略”
网络·智能路由器·信息与通信·nat·端口映射·公网ip
前端炒粉12 小时前
个人简历面经总结二
前端·网络·vue.js·react.js·面试
碎碎念_49213 小时前
ACL包过滤、NAT技术、广域网协议
服务器·网络·安全·acl·nat
techdashen13 小时前
把正确性藏进类型里:从 Go 的 io.Reader 到 Rust 的 API 设计
网络·golang·rust
AI-好学者13 小时前
MCP企业运用全面知识点-基础篇
服务器·开发语言·网络·人工智能·python·架构
happyprince14 小时前
18-vLLM 结构化输出约束分析文档
网络·vllm
yyuuuzz14 小时前
2026独立站运营的几个技术细节问题
运维·服务器·网络·人工智能·游戏
网络攻城狮_14 小时前
网络协议大全
运维·网络·网络协议·http