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。

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

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

相关推荐
全栈测试笔记4 小时前
FastAPI系列(02):第一个示例
fastapi
PieroPc1 天前
用FastAPI 和Html+css+js 写的 发票PDF文件管理系统
css·html·fastapi
钱彬 (Qian Bin)3 天前
项目实践17—全球证件智能识别系统(开发基于LabelMe标注的可视化审核接口)
qt·fastapi·全球证件识别
ghgxm5203 天前
Fastapi_00_学习策略与学习计划
python·学习·前端框架·npm·fastapi
我是菜鸟0713号4 天前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
a程序小傲4 天前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
风送雨4 天前
FastAPI 学习教程 · 第6部分
学习·fastapi
风送雨4 天前
FastAPI 学习教程 · 第5部分
jvm·学习·fastapi
越甲八千4 天前
FastAPI传参类型
开发语言·python·fastapi