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

相关推荐
白帽黑客沐瑶1 天前
【网络安全就业】信息安全专业的就业前景(非常详细)零基础入门到精通,收藏这篇就够了
网络·安全·web安全·计算机·程序员·编程·网络安全就业
树码小子1 天前
Java网络编程:(socket API编程:TCP协议的 socket API -- 回显程序的服务器端程序的编写)
java·网络·tcp/ip
绿箭柠檬茶1 天前
Ubuntu 服务器配置转发网络访问
服务器·网络·ubuntu
real 11 天前
传输层协议UDP
网络·网络协议·udp
路由侠内网穿透1 天前
本地部署 GPS 跟踪系统 Traccar 并实现外部访问
运维·服务器·网络·windows·tcp/ip
喵手2 天前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
徐子元竟然被占了!!2 天前
实验-基本ACL
网络
ftpeak2 天前
从零开始使用 axum-server 构建 HTTP/HTTPS 服务
网络·http·https·rust·web·web app
LabVIEW开发2 天前
LabVIEW气体污染无线监测
网络·labview·labview知识·labview功能·labview程序
error:(2 天前
【从零到公网】本地电脑部署服务并实现公网访问(IPv4/IPv6/DDNS 全攻略)
网络·智能路由器