一个简单的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 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
随身数智备忘录10 小时前
什么是设备管理体系?设备管理体系包含哪些核心模块?
网络·数据库·人工智能
第五文修10 小时前
手机OTG转TTL网口实现ping功能
网络·智能手机
云边云科技_云网融合10 小时前
企业大模型时代的网络架构五层演进:从连接到智能的范式重构
网络·重构·架构
xhbh66612 小时前
代理ARP (Proxy ARP) 是如何实现跨网段通信的?在Linux下如何配置?
服务器·网络·智能路由器·端口映射·映射
数智化管理手记13 小时前
精益生产3步实操,让现场从混乱变标杆
大数据·运维·网络·人工智能·精益工程
XiYang-DING14 小时前
【Java EE】TCP—可靠传输
网络·tcp/ip·java-ee
沃虎电子14 小时前
片式网络变压器:从“手工品”到“SMD元件”的产业跨越
网络·片式网络变压器
神奇小梵14 小时前
关于finalshell的使用
linux·服务器·网络
上海云盾-小余14 小时前
恶意爬虫精准拦截:网站流量净化与资源守护方案
网络·爬虫·web安全