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

相关推荐
旺仔.2916 小时前
Linux 信号详解
linux·运维·网络
源远流长jerry9 小时前
在 Ubuntu 22.04 上配置 Soft-RoCE 并运行 RDMA 测试程序
linux·服务器·网络·tcp/ip·ubuntu·架构·ip
虾..10 小时前
UDP协议
网络·网络协议·udp
w-w0w-w11 小时前
Unix网络编程
服务器·网络·unix
未知鱼11 小时前
Python安全开发之子域名扫描器(含详细注释)
网络·python·安全·web安全·网络安全
寂柒11 小时前
序列化与反序列化
linux·网络
志栋智能11 小时前
超自动化巡检:应对复杂IT环境的必然选择
运维·网络·安全·web安全·自动化
上海云盾-小余12 小时前
云主机安全加固:从系统、网络到应用的零信任配置
网络·安全·php
QCzblack13 小时前
见面考复现
网络
Eric.Lee202114 小时前
查看ubuntu机器正在使用的网络端口
网络·ubuntu·php