FastAPI 学习之路(五十一)WebSockets(七)实现一对一聊天

基于上一篇内容,其实这个一对一也比较简单,我们在之前的websockets管理中已经实现了一对一发消息的内容,这次呢,我们只需要实现一对一如何处理消息即可。

复制代码
import json


@app.websocket("/ws/{user}")
async def websocket_one_to_one(
        websocket: WebSocket,
        user: str,
        cookie_or_token: str = Depends(get_cookie_or_token)
):
    """一对一聊天"""
    await ws_manager.connect(user, websocket)
    try:
        while True:
            data = await websocket.receive_text()  # 前端发送的数据是:ws.send(input.value+"?"+username.value)
            await ws_manager.send_other_message(message=json.loads(data.split("?")[0]), user=data.split("?")[1])
    except WebSocketDisconnect as e:
        await ws_manager.disconnect(user, websocket)

其实也比较简单,还是之前的方法,只是对应的path不一样,而且要发送给用户的消息使用了"?"拼接,实际上,可以作为参数带过来,这只是讲个思路,并且我们要发送给的人也在前端页面选择或者填写。

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
</head>
<body>
<h1>WebSocket</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" value="要发送的消息" autocomplete="off"/>
      <input type="text" id="username" value="要发送的用户" autocomplete="off"/>
    <button>Send</button>
</form>
<button onclick="logout()">退出</button>
<ul id='messages'>
</ul>
<script>
    var  token=window.localStorage.getItem("token")
    if (token==null ){
        window.location.href="/login"
    }
    var ws = new WebSocket("ws://localhost:8000/ws/"+token+"?token="+token);

    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")
        var username = document.getElementById("username")

        ws.send(input.value+"?"+username.value)

        // input.value = ''

        event.preventDefault()

    }
    function logout() {
        window.localStorage.removeItem("token")
        window.location.href='/login'
    }
</script>

</body>

</html>

这里使用填写的方式,新增一个input标签,让用户来自己填写要发送给的用户,这样就完成了一个简单的一对一的聊天demo。

测试效果,分别登录两个用户,给对方发送消息:

可以看到消息已经接收成功,反之发送也是可以的,你也可以增加第三个人看是否能发送成功

相关推荐
Alan_757 小时前
Python FastAPI 高性能 API 开发:三个核心优化方向
api·fastapi
曲幽5 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
CaffeinePro7 天前
依赖注入:FastAPI最核心的解耦能力案例解析
后端·fastapi
曲幽11 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
CaffeinePro14 天前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
jay神16 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
染指111017 天前
6.AI大模型-搭建本地大模型服务体系
fastapi·oneapi
codeaideaai19 天前
使用UV创建python项目
python·fastapi·uv
放下华子我只抽RuiKe519 天前
FastAPI 全栈后端(八):部署与运维
运维·数据库·react.js·oracle·数据挖掘·前端框架·fastapi
SilentSamsara19 天前
模型部署实战:FastAPI + ONNX + Docker 的推理服务化
人工智能·pytorch·python·深度学习·机器学习·fastapi