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

相关推荐
楚韵天工2 小时前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
疯狂吧小飞牛4 小时前
ip rule 策略路由
linux·网络·tcp/ip·运维开发
hour_go5 小时前
TCP/IP协议相关知识点
网络·笔记·网络协议·tcp/ip
Arva .5 小时前
WebSocket实现网站点赞通知
网络·websocket·网络协议
雪兽软件5 小时前
SaaS 安全是什么以及如何管理风险
网络·安全
纸带6 小时前
USB -- SET_ADDRESS or --SET_ADDRESS or --SET_CONFIGURATION or --SET_INTERFACE
网络
white-persist6 小时前
CSRF 漏洞全解析:从原理到实战
网络·python·安全·web安全·网络安全·系统安全·csrf
嫄码6 小时前
TCP/IP 四层模型
网络·网络协议·tcp/ip
游戏开发爱好者86 小时前
FTP 抓包分析实战,命令、被动主动模式要点、FTPS 与 SFTP 区别及真机取证流程
运维·服务器·网络·ios·小程序·uni-app·iphone
liebe1*16 小时前
第三章 常用协议
网络