一个简单的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 分钟前
GORM钩子函数详解
网络·安全·web安全
汇智信科1 小时前
图谱、向量、关键词、SQL多路一体,FastKG垂域召回率100%拉满
网络·数据库·ai编程·汇智信科·hsim·fastclaw·汇智龙虾
liulilittle1 小时前
论分布式系统的半开闭问题
服务器·网络·分布式·系统架构·竞态
FreeBuf_2 小时前
仅用六分钟,黑客借助Gemini CLI自主构建并迁移C&C僵尸网络
网络·人工智能
cyforkk2 小时前
Vercel 绑定自定义域名极简配置指南
服务器·前端·网络
Yang96113 小时前
探索无线新视界:鼎讯信通DXMP系列频谱仪模块深度剖析
运维·网络
进阶的猪5 小时前
【无标题】vmware虚拟机无法勾选**将主机虚拟适配器连接到此网络** /没有网络(不显示网络图标)的解决方法
网络
CHANG_THE_WORLD6 小时前
6.多线程的TCP通信
java·网络·tcp/ip
信仰8746 小时前
Linux进阶篇01:网络基础配置
linux·网络·php
宠友信息6 小时前
MySQL复合索引与Druid优化仿小红书源码个人主页查询链路
数据库·spring boot·websocket·mysql·uni-app