• FastAPI WebSocket 简单演示


    WebSocket 服务

    使用Python FastAPI框架官网demo,官网地址:https://fastapi.tiangolo.com/zh/advanced/websockets/

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @time: 2021/12/9 6:30 下午
    import uvicorn
    from typing import List
    
    from fastapi import FastAPI, WebSocket, WebSocketDisconnect
    from fastapi.responses import HTMLResponse
    
    app = FastAPI()
    
    html = """
    <!DOCTYPE html>
    <html>
        <head>
            <title>Chat</title>
        </head>
        <body>
            <h1>WebSocket Chat</h1>
            <h2>Your ID: <span id="ws-id"></span></h2>
            <form action="" onsubmit="sendMessage(event)">
                <input type="text" id="messageText" autocomplete="off"/>
                <button>Send</button>
            </form>
            <ul id='messages'>
            </ul>
            <script>
                var client_id = Date.now()
                document.querySelector("#ws-id").textContent = client_id;
                var ws = new WebSocket(`ws://localhost:8010/ws/${client_id}`);
                ws.onmessage = function(event) {
                    var messages = document.getElementById('messages')
                    var message = document.createElement('li')
                    var content = document.createTextNode(event.data)
                    message.appendChild(content)
                    messages.appendChild(message)
                };
                function sendMessage(event) {
                    var input = document.getElementById("messageText")
                    ws.send(input.value)
                    input.value = ''
                    event.preventDefault()
                }
            </script>
        </body>
    </html>
    """
    
    
    class ConnectionManager:
        def __init__(self):
            self.active_connections: List[WebSocket] = []
    
        async def connect(self, websocket: WebSocket):
            await websocket.accept()
            self.active_connections.append(websocket)
    
        def disconnect(self, websocket: WebSocket):
            self.active_connections.remove(websocket)
    
        @classmethod
        async def send_personal_message(cls, message: str, websocket: WebSocket):
            await websocket.send_text(message)
    
        async def broadcast(self, message: str, websocket: WebSocket = None):
            for connection in self.active_connections:
                if connection != websocket:
                    await connection.send_text(message)
    
    
    manager = ConnectionManager()
    
    
    @app.get("/")
    async def get():
        return HTMLResponse(html)
    
    
    @app.websocket("/ws/{client_id}")
    async def websocket_endpoint(websocket: WebSocket, client_id: int):
        await manager.connect(websocket)
        try:
            while True:
                data = await websocket.receive_text()
                await manager.send_personal_message(f"你说了: {data}", websocket)
                await manager.broadcast(f"用户:{client_id} 说: {data}", websocket)
    
        except WebSocketDisconnect:
            manager.disconnect(websocket)
            await manager.broadcast(f"用户-{client_id}-离开")
    
    
    if __name__ == '__main__':
        uvicorn.run('main:app', debug=True, host='0.0.0.0', port=8010)
  • 相关阅读:
    虚函数和纯虚函数
    MS CRM 2011中PartyList类型字段的实例化
    MS CRM 2011的自定义与开发(12)——表单脚本扩展开发(4)
    MS CRM 2011的自定义与开发(12)——表单脚本扩展开发(2)
    MS CRM 2011的自定义和开发(10)——CRM web服务介绍(第二部分)——IOrganizationService(二)
    MS CRM 2011 SDK 5.08已经发布
    MS CRM 2011 Q2的一些更新
    最近很忙
    Microsoft Dynamics CRM 2011最近的一些更新
    补一篇,Update Rollup 12 终于发布了
  • 原文地址:https://www.cnblogs.com/root0/p/15668887.html
Copyright © 2020-2023  润新知