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

相关推荐
LRX_1989271 分钟前
华为设备配置练习(七)VRRP 配置
服务器·网络·华为
广东大榕树信息科技有限公司28 分钟前
如何实现动环监控系统的国产化与智能化?
运维·网络·物联网·国产动环监控系统·动环监控系统
王景程38 分钟前
基于CSI接口的摄像机模块
网络
云飞云共享云桌面1 小时前
10个SolidWorks研发设计共享一台工作站——昆山精密机械工厂降本增效一举三得
网络
1024肥宅1 小时前
浏览器网络请求 API:全面解析与高级封装(1)
前端·websocket·axios
1024肥宅1 小时前
浏览器网络请求 API:全面解析与高级封装(2)
前端·websocket·axios
Bruce_Liuxiaowei1 小时前
SSH主机密钥验证失败(Host key verification failed)深度解析与解决方案
运维·网络·ssh
星瞰物联2 小时前
融合北斗与天通卫星通信技术的堤坝水文监测卫星图传系统
网络·物联网·安全·系统架构
周杰伦_Jay3 小时前
【GRPC 和 HTTP】设计目标和底层实现
网络·网络协议·http
木子欢儿4 小时前
Prometheus Blackbox域名SSL证书监控并设置AlertManager告警
网络·网络协议·ssl·prometheus