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

相关推荐
聚铭网络5 小时前
聚铭网络成功入围徐州市大数据集团2026年业务类合作供应商名录(第一批次)
大数据·网络
hy____1236 小时前
Linux_网络基础3
linux·服务器·网络
Striver-Diligent7 小时前
GenNP: 一种低门槛且功能强大的网络性能数据生成器
网络·计算机网络·并行·网络仿真·网络性能估计·离散事件仿真
带娃的IT创业者7 小时前
Weclaw 请求路由实战:一个 request_id 如何在 800 个并发连接中精准找到目标浏览器?
python·websocket·fastapi·架构设计·实时通信·openclaw·weclaw
望未来无悔8 小时前
实时传输的选择方案
websocket
我是唐青枫10 小时前
C#.NET ReadOnlySequence 深入解析:多段内存遍历与零拷贝协议解析
网络·c#·.net
带娃的IT创业者11 小时前
WeClaw 心跳与重连实战:指数退避算法如何让 WebSocket 在弱网环境下的连接成功率提升 67%?
python·websocket·网络协议·算法·fastapi·实时通信
Insist75312 小时前
案例二---集群修改物理IP和VIP
运维·网络·数据库
qq_4112624212 小时前
在建立udp连接的时候,有时候能成功,有时候AT 指令返回+ERRNO:0x70
网络·网络协议·udp
专家大圣13 小时前
告别智能家居品牌壁垒✨ Home Assistant+cpolar 让远程控家更省心
网络·docker·智能家居·内网穿透·cpolar