相关文章推荐
聪明伶俐的甘蔗  ·  让音乐架起中美友好的桥梁_中华人民共和国驻纽 ...·  1 年前    · 
豁达的红烧肉  ·  将SQLServer中的负数varchar和 ...·  2 年前    · 
好帅的海龟  ·  这一次,89岁谷建芬老师忍无可忍,她坚决发表 ...·  3 年前    · 
兴奋的铅笔  ·  电动微型车5月销量暴跌40%,让人不禁想问: ...·  3 年前    · 
乐观的西红柿  ·  我被地球绑架了漫画|官方在线漫画全集-快看漫画·  3 年前    · 
Code  ›  FastAPI 学习之路(五十一)WebSockets(八)接受/发送json格式消息开发者社区
科技新闻 websocket
https://cloud.tencent.com/developer/article/1887944
激动的抽屉
3 年前
作者头像
雷子
0 篇文章

FastAPI 学习之路(五十一)WebSockets(八)接受/发送json格式消息

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > 雷子说测试开发 > FastAPI 学习之路(五十一)WebSockets(八)接受/发送json格式消息

FastAPI 学习之路(五十一)WebSockets(八)接受/发送json格式消息

作者头像
雷子
发布 于 2021-10-12 16:23:15
1.3K 0
发布 于 2021-10-12 16:23:15
举报

前言

上一篇我们分享了 FastAPI 学习之路(五十)WebSockets(七)实现一对一聊天 ,那么我们今天来实现呢,websockets接受和发送json格式消息。

正文

相对于之前的text的消息来说,我们之前发送的消息都是text的居多,那么对于text格式的消息来说,我们处理起来,尤其是后端要麻烦的多,那么我们可不可以传递json格式的,对于前后端来说都好处理的一种格式的消息,那么答案来说是可以的。我们需要做下处理。

我们在之前的websockets管理中的的消息的处理全部改造成json格式的。我们看下如何处理呢 class ConnectionManager: def __init__(self): # 存放**的链接 self.active_connections: List[Dict[str, WebSocket]] = [] async def connect(self, user: str, ws: WebSocket): await ws.accept() self.active_connections.append({"user": user, "ws": ws}) def disconnect(self, user: str, ws: WebSocket): # 关闭时 移除ws对象 self.active_connections.remove({"user": user, "ws": ws}) async def send_other_message_json(self, message: dict, user: str): # 发送个人消息 for connection in self.active_connections: if connection["user"] == user: await connection['ws'].send_json(message) async def broadcast_json(self, data: dict): # 广播消息 for connection in self.active_connections: await connection['ws'].send_json(data)

我们现在所有的消息,我们只支持的json格式呢,我们可以对的处理消息,


manager = ConnectionManager()
@app.websocket("/ws/{user}/")
async  def websocket_many_point(
        websocket: WebSocket,
        user:str,
        cookie_or_token: str = Depends(get_cookie_or_token),
    print(user)
    await manager.connect(user, websocket)
        while True:
            data = await websocket.receive_json()
            senduser=data['username']
            if senduser:
                await manager.send_other_message_json(data,senduser)
            else:
                await  manager.broadcast_json(data)
    except WebSocketDisconnect as e:
        manager.disconnect(user, websocket)

‍ 修改完之后,我们针对前段也需要修改,修改成支持我们的json格式数据

<!DOCTYPE html>
    <title>Chat</title>
</head>
<h1>WebSocket 聊天</h1>
<form action="" onsubmit="sendMessage(event)">
    <input type="text" id="messageText" autocomplete="off"/>
      <input type="text" id="username" autocomplete="off"/>
    <button>Send</button>
</form>
<button onclick="logout()">退出</button>
<ul id='messages'>
<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')
        let receiveJson = JSON.parse(event.data);
        console.log(receiveJson)
        var content = document.createTextNode(receiveJson.username+"说:"+receiveJson.messageText)
        message.appendChild(content)
        messages.appendChild(message)
    function sendMessage(event) {
        var input = document.getElementById("messageText")
        var username = document.getElementById("username")
        let message = {messageText: input.value, username:username.value};
        let messageJson = JSON.stringify(message);
        ws.send(messageJson);
        input.value = ''
        event.preventDefault()
    function logout() {
        window.localStorage.removeItem("token")
        window.location.href='/login'
</script>
 
推荐文章
聪明伶俐的甘蔗  ·  让音乐架起中美友好的桥梁_中华人民共和国驻纽约总领事馆
1 年前
豁达的红烧肉  ·  将SQLServer中的负数varchar和null值转换为decimal -火山引擎
2 年前
好帅的海龟  ·  这一次,89岁谷建芬老师忍无可忍,她坚决发表律师声明|那英|刀郎|歌曲|刘欢|杨坤|新歌|毛阿敏_网易订阅
3 年前
兴奋的铅笔  ·  电动微型车5月销量暴跌40%,让人不禁想问:为何买的人越来越少?|小型车|奇瑞汽车|吉利熊猫|五菱宏光|宝骏汽车_网易订阅
3 年前
乐观的西红柿  ·  我被地球绑架了漫画|官方在线漫画全集-快看漫画
3 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号