我有一些问题。我目前正在使用flask -socketio做一个聊天应用程序 一切都很正常 但我想增加一个功能 让最近加入一个房间的用户 可以看到他们加入之前的聊天记录 我真的是在摸索这个功能的逻辑。下面是我做的。问题是我如何循环播放被发送到前端的聊天记录,或者有什么更好的方法吗?
@socketio.on('join')
def join(data):
join_room(data['room'])
room_name = data['room']
chats = engine.execute(text(
"""SELECT * FROM chat_history WHERE room = :room_name"""), ({"room_name": room_name},)).fetchall()
if chats:
send({'msg': data['username'] + " has joined the " + data['room'] + " room."}, room=data['room'], chats=chats)
您需要将新用户公告和聊天记录分开,因为公告会发给房间里的所有人,但聊天记录只发给加入的用户。
您可以继续用发送来宣布用户,但是可以使用 emit()
的专用事件,其中您可以将聊天记录作为参数。
# announce the new user as before
send({'msg': data['username'] + " has joined the " + data['room'] + " room."}, room=data['room'])
# pass chat history to the new user (note there is no room argument on this one)
emit('joined', chats)
然后在客户端添加一个处理程序来处理 joined
事件,然后你就可以呈现你的聊天记录了。
我希望这是有意义的