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

相关推荐
南棱笑笑生2 小时前
20260310在瑞芯微原厂RK3576的Android14查看系统休眠时间
服务器·网络·数据库·rockchip
yy55273 小时前
LNAMP 网络架构与部署
网络·架构
Godspeed Zhao4 小时前
现代智能汽车系统——CAN网络2
网络·汽车
爱丽_4 小时前
Docker 从原理到项目落地(镜像 / 容器 / 网络 / 卷 / Dockerfile)
网络·docker·容器
眼镜哥(with glasses)5 小时前
网络技术三级考试综合题笔记整理(第二题、第三题)
网络·笔记·智能路由器
Johnstons5 小时前
读懂 TCP 标志位:网络运维中的“信号灯”
运维·网络·tcp/ip
小哇6665 小时前
第2篇:Spring Boot + WebSocket + 消息队列STOMP协议(Rabbitmq) 架构原理
后端·websocket
半壶清水5 小时前
[软考网规考点笔记]-数据通信基础之差错控制编码技术
网络·笔记·网络协议·tcp/ip
坚定的共产主义生产设备永不宕机5 小时前
网络层协议(IPV4报头)
运维·服务器·网络
王燕龙(大卫)7 小时前
通过文心快码,2小时完成一周的工作量
服务器·网络·tcp/ip