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

相关推荐
承渊政道15 小时前
Linux网络学习【Reactor反应堆模式】
linux·网络·学习·ubuntu·reactor
爱和冰阔落20 小时前
【Linux网络】TCP 服务器如何并发处理多个客户端?从 fork、僵尸进程到双重 fork
linux·运维·服务器·网络
严肃小白兔21 小时前
Cloudflare 更新 API Token 管理:从最小权限到自动化凭据安全
网络·安全·自动化
Linux-lucky1 天前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
博客zhu虎康2 天前
实现局域网P2P通信:内网发送消息
网络·网络协议·p2p
吴声子夜歌2 天前
Kubernetes权威指南——网络原理(一)
网络·容器·kubernetes
陈希1232 天前
Linux 服务器性能排查手册(2026):CPU、内存、磁盘IO、网络四大瓶颈定位
linux·服务器·网络
国科安芯2 天前
从遥控到自治:ASP4644S2B支撑星载电源健康管理与容错配电
网络·单片机·嵌入式硬件·安全·dcdc·低轨卫星·商业航天
|_⊙2 天前
网络层协议 IP
服务器·网络·tcp/ip
无言听风雨丶2 天前
Kubernetes Service Mesh 与 mTLS 实战:从网络可达走向零信任服务通信
网络·kubernetes·service_mesh