FastAPI 学习之路(五十一)WebSockets(八)接受/发送json格式消息
前言
上一篇我们分享了 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>