flask + websocket实现简单的单聊和群聊
单聊
from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket import json app = Flask(__name__) user_socket_dict = {} @app.route('/ws/<username>') def ws(username): user_socket = request.environ.get('wsgi.websocket') # type:WebSocket user_socket_dict[username] = user_socket print(len(user_socket_dict),user_socket_dict) while 1: try: msg = user_socket.receive() msg = json.loads(msg) to_user = msg.get('to_user') content = msg.get('msg') usocket = user_socket_dict.get(to_user) recv_msg = { 'from_user':username, 'msg':content } usocket.send(json.dumps(recv_msg)) except: pass @app.route('/chat') def chat(): return render_template('chat.html') if __name__ == '__main__': http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler) http_serv.serve_forever()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>单聊</title> </head> <body> <input type="text" id="username"> <button onclick="open_ws()">连接服务器</button> <p>给:<input type="text" id="to_user"></p> <p>发送消息:<input type="text" id="msg"></p> <button onclick="send_msg()">发送</button> <div id="chat" style="width: 500px; height: 500px;"></div> <script type="text/javascript"> var ws = null; function open_ws() { var username = document.getElementById('username').value; ws = new WebSocket('ws://192.168.19.34:5000/ws/' + username); ws.onmessage = function (data) { var msg = JSON.parse(data.data); var ptag = document.createElement('p'); ptag.innerText = msg.from_user + ':' + msg.msg; document.getElementById('chat').appendChild(ptag); }; } function send_msg() { var msg = document.getElementById('msg').value; var to_user = document.getElementById('to_user').value; var send_obj = {to_user:to_user,msg:msg}; ws.send(JSON.stringify(send_obj)); } </script> </body> </html>
群聊
#!/usr/bin/env python # -*- coding=utf-8 -*- from flask import Flask,request,render_template from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket import json app = Flask(__name__) user_socket_list = [] @app.route('/ws') def ws(): user_socket = request.environ.get('wsgi.websocket') # type:WebSocket user_socket_list.append(user_socket) print(len(user_socket_list),user_socket_list) while 1: try: msg = user_socket.receive() for usocket in user_socket_list: if usocket != user_socket: usocket.send(msg) except: user_socket_list.remove(user_socket) @app.route('/chat') def chat(): return render_template('ws.html') if __name__ == '__main__': http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler) http_serv.serve_forever()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>发送消息:<input type="text" id="msg"></p> <button onclick="send_msg()">发送</button> <div id="chat" style="width: 500px;height: 500px;"></div> <script type="text/javascript"> var ws = new WebSocket('ws://192.168.19.34:5000/ws'); ws.onmessage = function (data) { var ptag = document.createElement('p'); ptag.innerText = data.data; document.getElementById('chat').appendChild(ptag); }; function send_msg() { var msg = document.getElementById('msg').value; ws.send(msg) } </script> </body> </html>