Flask实现简单的群聊和单聊
Flask是使用python写的一个简单轻量级的框架,今天我们使用Flask实现一个简单的单聊和群聊功能 .
主要思路 : 前端登录聊天室,聊天室信息包含用户的登录信息,相当于一个登录功能,会把这个信息记录在url中发送给后端,后端会把登录信息作为识别用户的标志,url中的信息会作为key值存在一个字典中:
{'111':
单聊也是基于这个key值实现的,如果发送的用户为空则默认为群聊;
一.导入相关的包并实例化一个Flask对象
import json
from flask import Flask, request, render_template
from geventwebsocket.handler import WebSocketHandler
from gevent.pywsgi import WSGIServer
from geventwebsocket.websocket import WebSocket
app = Flask(__name__) #实例化一个Flask对象
user_socket_dict = {} #创建一个空字典
二.后端通过request.environ获取前端的所有信息,其中wsgi.websocket对应的值即用户对象,取出这个对象存入字典 :
@app.route('/ws_app/') #设置Flask路由,前端通过访问这个地址拆解信息,即前端登录聊天室输入的内容
def ws_app(user_nick):
user_socket = request.environ.get("wsgi.websocket") # type:WebSocket #取出environ中的wsgi.websocket对应的值
user_socket_dict[user_nick] = user_socket #以为key在字典中插入用户信息
print(user_socket_dict) #{'111': , '222': }
三.通过receive取出用户要发送的内容并进行json转换,通过get方法取出to_user(要发送的对象的聊天号),如果没有返回0,后边再通过if判断区别单聊还是群聊:如果to_user存在,说明要发给单个用户,否则是群发.
while True:
msg = user_socket.receive() #取出发送内容
msg_dict = json.loads(msg)
to_user = msg_dict.get("to_user",0) #没有返回0
if to_user: #有发送对象 单聊
to_user_socket = user_socket_dict.get(to_user) #用get方法取出
to_user_socket.send(msg)
else: #没有发送对象 群聊
for usocket in list(user_socket_dict.values()):
usocket.send(msg)
@app.route('/')
def index():
return render_template('my_ws.html')
if __name__ == '__main__':
http_serve = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler)
http_serve.serve_forever()
四.前端代码
1 2"text" id="nick"> 3 4
5 发送给:"text" id="to_user">消息:"text" id="send_str"> 6 78
"chat_list"> 9 1011 12 13