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。

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

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

相关推荐
simon_skywalker5 小时前
FastAPI实战笔记(六)集成SQL数据库
fastapi
前端初见9 小时前
FastAPI框架入门教程
fastapi
越甲八千1 天前
简单fastapi和压测实例
adb·fastapi
逻极1 天前
FastAPI + SQLAlchemy 现代API项目实战:从零到上手的Python MySQL开发指南
python·mysql·fastapi·异步·sqlalchemy
仅此,1 天前
Java请求进入Python FastAPI 后,请求体为空,参数不合法
java·spring boot·python·组合模式·fastapi
Biehmltym1 天前
【AI】07 AI Agent可控风格LLM 问答(含FastAPI 求/返回/路由、跨域访问CORS、System Prompt)
人工智能·prompt·fastapi
Biehmltym1 天前
【AI】08 AI Agent FastAPI + LLM 进阶:基于 Session 的多轮对话| 规则优先 + Tool 调用Agent实现
人工智能·fastapi
曲幽1 天前
一文理清FastAPI参数:从Query、Path到BaseModel的实战指南
python·fastapi·web·form·request·path·body·query·basemodel
vibag2 天前
FastAPI框架
python·pycharm·fastapi
爱敲代码的TOM3 天前
PythonWeb基础-FastAPI使用
python·fastapi