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。

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

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

相关推荐
掘金-我是哪吒1 天前
分布式微服务系统架构第131集:fastapi-python
分布式·python·微服务·系统架构·fastapi
Anesthesia丶3 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779133 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒3 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn4 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教4 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教4 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779135 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI8 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi
Data 实验室11 天前
爬虫管理平台-最新版本发布
开发语言·爬虫·python·fastapi