单聊
1 from flask import Flask,request,render_template 2 from geventwebsocket.handler import WebSocketHandler 3 from gevent.pywsgi import WSGIServer 4 from geventwebsocket.websocket import WebSocket 5 import json 6 7 8 app = Flask(__name__) 9 10 user_socket_dict = {}11 12 @app.route('/ws/')13 def ws(username):14 user_socket = request.environ.get('wsgi.websocket') # type:WebSocket15 user_socket_dict[username] = user_socket16 17 print(len(user_socket_dict),user_socket_dict)18 19 while 1:20 try:21 msg = user_socket.receive()22 msg = json.loads(msg)23 to_user = msg.get('to_user')24 content = msg.get('msg')25 usocket = user_socket_dict.get(to_user)26 recv_msg = {27 'from_user':username,28 'msg':content29 }30 31 usocket.send(json.dumps(recv_msg))32 except:33 pass34 35 @app.route('/chat')36 def chat():37 return render_template('chat.html')38 39 40 if __name__ == '__main__':41 http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler)42 http_serv.serve_forever()43 44 python代码
1 2 3 4 5单聊 6 7 8 9 10给:
11发送消息:
12 13 14 15 35 36 37 38 39 40 页面
群聊
1 #!/usr/bin/env python 2 # -*- coding=utf-8 -*- 3 from flask import Flask,request,render_template 4 from geventwebsocket.handler import WebSocketHandler 5 from gevent.pywsgi import WSGIServer 6 from geventwebsocket.websocket import WebSocket 7 import json 8 9 app = Flask(__name__)10 11 user_socket_list = []12 13 @app.route('/ws')14 def ws():15 user_socket = request.environ.get('wsgi.websocket') # type:WebSocket16 user_socket_list.append(user_socket)17 print(len(user_socket_list),user_socket_list)18 while 1:19 try:20 msg = user_socket.receive()21 for usocket in user_socket_list:22 if usocket != user_socket:23 usocket.send(msg)24 except:25 user_socket_list.remove(user_socket)26 27 28 @app.route('/chat')29 def chat():30 return render_template('ws.html')31 32 if __name__ == '__main__':33 http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler)34 http_serv.serve_forever()35 36 Python代码
1 2 3 4 5Title 6 7 8发送消息:
9 10 11 24 25 26 27 页面