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

相关推荐
通信大模型6 小时前
IEEE TCCN | 面向低空经济网络的Agentic AI驱动多无人机轨迹优化
网络·人工智能·无人机
wdfk_prog7 小时前
LWIP教程 09:从 `tcp_slowtmr()` 到 Fast Retransmit——TCP 超时重传与重复 ACK
服务器·网络·数据库·网络协议·tcp/ip
15Moonlight7 小时前
Linux网络(02):Socket 编程 UDP
linux·网络·udp
盛世宏博智慧档案7 小时前
一文读懂 PoE+Modbus TCP 温湿度传感器布线规范与故障排查
网络·网络协议·tcp/ip
liulilittle8 小时前
Linux 下 select 测试函数
linux·服务器·网络·数据库·c++·select·c
夜雪一千8 小时前
Python 生成模拟地址数据:Faker之外的备选库
网络·windows·python
小此方8 小时前
Linux网络(二十一):深入理解 TCP 异常处理:网线断开、Keepalive 保活机制与 Linux 内核传输层协议源码剖析
linux·网络·tcp/ip
北京盛世宏博8 小时前
工业环境监测选型:Modbus TCP以太网温湿度传感器部署、调试、避坑全指南
开发语言·网络·php
Raspberry_Pi_官方账号9 小时前
Raspberry Pi Desktop 全面升级,现已登陆 PC 和 Mac
服务器·网络·macos·树莓派·raspberry pi·raspberrypios