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服务。