首页 > 其他分享 >websocket and fastapi

websocket and fastapi

时间:2024-12-04 23:25:20浏览次数:12  
标签:websocket fastapi await redis server async channel

 

This project demonstrates how to use socket.io with FastAPI and React

https://github.com/jrdeveloper124/socketio-app/tree/main

 

You can use WebSockets with FastAPI.

https://fastapi.tiangolo.com/advanced/websockets/

https://stackoverflow.com/questions/71827145/broadcasting-a-message-from-a-manager-to-clients-in-websocket-using-fastapi

 

How to send messages from server to client in a Python WebSockets server, AFTER initial handshake?

https://stackoverflow.com/questions/74988529/how-to-send-messages-from-server-to-client-in-a-python-websockets-server-after

import asyncio
import datetime
from typing import Iterator
import websockets
import random

websocket_connections = set()
sock_port = 8000
sock_url = 'localhost'
global_socket = lambda: None

async def register(websocket):
    print('register event received')
    websocket_connections.add(websocket) # Add this client's socket
    global_socket = websocket

async def poll_log():
    await asyncio.sleep(0.3) # Settle
    while True:
        await asyncio.sleep(0.3) # Slow things down
        
        # Send a dynamic message to the client after random delay
        r = random.randint(1, 10)
        if (r == 5): # Only send 10% of the time
            a_msg = "srv -> cli: " + str(random.randint(1,10000))
            print("sending msg: " + a_msg)
            websockets.broadcast(websocket_connections, a_msg) # Send to all connected clients
        
async def main():
    sock_server = websockets.serve(register, sock_url, sock_port)
    await asyncio.sleep(0.3) # Start up time
    async with sock_server: await poll_log()

if __name__ == "__main__":
    print("Websockets server starting up ...")
    asyncio.run(main())

 

websocket-example

https://github.com/ustropo/websocket-example/tree/main

 

Scaling WebSocket applications

https://unfoldai.com/fastapi-and-websockets/

 

import aioredis
from fastapi import FastAPI, WebSocket

app = FastAPI()

async def get_redis():
    redis = await aioredis.create_redis_pool("redis://localhost")
    return redis

@app.websocket("/ws/redis/{channel}")
async def websocket_endpoint(websocket: WebSocket, channel: str):
    await websocket.accept()
    redis = await get_redis()
    try:
        channel = await redis.subscribe(channel)
        async for message in channel[0].iter():
            await websocket.send_text(message.decode())
    finally:
        await redis.unsubscribe(channel)
        redis.close()
        await redis.wait_closed()

@app.post("/publish/{channel}")
async def publish(channel: str, message: str):
    redis = await get_redis()
    await redis.publish(channel, message)
    return {"message": "Published"}

 

 

useEffect

https://www.ruanyifeng.com/blog/2020/09/react-hooks-useeffect-tutorial.html

 

标签:websocket,fastapi,await,redis,server,async,channel
From: https://www.cnblogs.com/lightsong/p/18587458

相关文章

  • ai-assistant stream with websocket.
    ai-assistantstreamwithwebsocket. https://github.com/dpills/ai-assistant/blob/master/main.pyfromtypingimportAsyncGenerator,NoReturnimportuvicornfromdotenvimportload_dotenvfromfastapiimportFastAPI,WebSocketfromfastapi.responsesimp......
  • Node.js实现WebSocket教程
    Node.js实现WebSocket教程1.WebSocket简介WebSocket是一种在单个TCP连接上提供全双工通信的协议,允许服务器和客户端之间进行实时、双向通信。本教程将详细讲解如何在Node.js中实现WebSocket。2.技术选型我们将使用ws库来实现WebSocket服务器,并结合express创建Web应用......
  • 说说轮询、长轮询、长连接、socket连接、WebSocket的区别
    在前端开发中,轮询、长轮询、长连接、Socket连接和WebSocket都是用于实现客户端和服务器之间实时或近实时通信的技术,但它们的工作方式和适用场景有所不同。1.轮询(Polling):原理:客户端定期向服务器发送请求,询问是否有新数据。如果有,服务器返回数据;如果没有,服务器返回空或......
  • Websocket++ 框架
    概述基于C++标准的WebSocket协议实现,适合使用C++11或更高版本开发的项目,支持构建WebSocket客户端和服务器,功能灵活,设计模块化,非常适合高性能的网络通信场景主要特点支持WebSocket客户端和服务器默认支持同步和异步I/O;可以与Boost.Asio或其他异步I/O库集成,......
  • 实时行情数据源接口websocket接入方法
    首先获取以下产品的代码:外汇国际期货国际期货国内期货国际金银数字货币股指期货 取到产品代码后,websocket就可以连接了。将产品代码推送到连接的服务器,服务器会实时推送最新的行情数据产品代码 :恒指期货HSI德指期货DAX英镑美元fx_sgbpusd欧元美元fx_seurusd ......
  • 了解HTTP请求、HTTP轮询、websocket、SSE通信方式
    了解浏览器和服务器通信的方法http请求http请求就是客户端向服务器发送请求,服务器响应,完成请求就断开连接。优点:操作简单,几乎所有浏览器都支持。缺点:HTTP是无状态的,服务器无法跟踪客户端的状态信息。http轮询原理:客户端每隔一段时间向服务器发送http请求,服务器收到请求......
  • FastHtml:Websockets
    FastHTML支持WebSockets,允许你与客户端建立持久连接并进行双向通信。以下是如何使用WebSockets进行双向通信的示例:fromfasthtml.commonimport*fromasyncioimportsleepapp,rt=fast_app(exts='ws')#启用WebSocket支持defmk_inp():returnInput(id='m......
  • 基于uniapp的全局监听websocket连接及自动拨打电话号码
    定义一个全局的socket类,放在util目录下//定义一个socket类classWebSocket{constructor(url){this.url=urlthis.time=null;}//建立连接connet(){let_this=this;uni.connectSocket({url:_this.u......
  • WebSocket入门到精通,就差这一篇了
    目录一、概述二、对比Http(介绍特点)1.通信模式对比2.连接机制3.数据传输效率4.实时性5.使用场景三、websocket通信原理1、建立连接连接1.客户端发起HTTP请求2.服务器处理请求并响应3.升级到WebSocket协议4.双向通信2、通信内容(websocket帧)1.Heade......
  • 三周精通FastAPI:14 表单数据和表单模型Form Models
     官网文档:表单数据-FastAPI表单数据¶接收的不是JSON,而是表单字段时,要使用 Form表单。fromfastapiimportFastAPI,Formapp=FastAPI()@app.post("/login/")asyncdeflogin(username:str=Form(),password:str=Form()):return{"username":user......