一个简单的websocket服务

参考: https://pypi.org/project/websockets/

#!/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的方法

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. 一个简单websocket服务

    2024-05-03 01:18:01       26 阅读
  2. Golang 实现一个简单 RPC 服务

    2024-05-03 01:18:01       44 阅读
  3. Node.js创建一个简单服务器

    2024-05-03 01:18:01       65 阅读
  4. Linux服务器配置一个简单DNS

    2024-05-03 01:18:01       27 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-03 01:18:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-03 01:18:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-05-03 01:18:01       82 阅读
  4. Python语言-面向对象

    2024-05-03 01:18:01       91 阅读

热门阅读

  1. Python实战开发及案例分析(1)——Web开发

    2024-05-03 01:18:01       29 阅读
  2. 机器学习-什么是 PCA?

    2024-05-03 01:18:01       29 阅读
  3. [leetcode]最多公共前缀

    2024-05-03 01:18:01       31 阅读
  4. 数据库索引(Mysql)

    2024-05-03 01:18:01       32 阅读
  5. 【C】190 颠倒二进制位

    2024-05-03 01:18:01       37 阅读
  6. 【SSL 1967】A和B

    2024-05-03 01:18:01       27 阅读