单聊
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/<username>')13 def ws(username):14user_socket = request.environ.get('wsgi.websocket') # type:WebSocket15user_socket_dict[username] = user_socket16 17print(len(user_socket_dict),user_socket_dict)18 19while 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():37return render_template('chat.html')38 39 40 if __name__ == '__main__':41http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler)42http_serv.serve_forever()43 44 python代码
代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4<meta charset="UTF-8"> 5<title>单聊</title> 6 </head> 7 <body> 8<input type="text" id="username"> 9<button οnclick="open_ws()">连接服务器</button>10<p>给:<input type="text" id="to_user"></p>11<p>发送消息:<input type="text" id="msg"></p>12<button οnclick="send_msg()">发送</button>13<div id="chat" style="width: 500px; height: 500px;"></div>14 15<script type="text/javascript">16 var ws = null;17 function open_ws() {18 var username = document.getElementById('username').value;19 ws = new WebSocket('ws://192.168.19.34:5000/ws/' + username);20 ws.onmessage = function (data) {21 var msg = JSON.parse(data.data);22 var ptag = document.createElement('p');23 ptag.innerText = msg.from_user + ':' + msg.msg;24 document.getElementById('chat').appendChild(ptag);25 };26 }27 28 function send_msg() {29 var msg = document.getElementById('msg').value;30 var to_user = document.getElementById('to_user').value;31 var send_obj = {to_user:to_user,msg:msg};32 ws.send(JSON.stringify(send_obj));33 }34</script>35 </body>36 37 38 </html>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():15user_socket = request.environ.get('wsgi.websocket') # type:WebSocket16user_socket_list.append(user_socket)17print(len(user_socket_list),user_socket_list)18while 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():30return render_template('ws.html')31 32 if __name__ == '__main__':33http_serv = WSGIServer(('0.0.0.0',5000),app,handler_class=WebSocketHandler)34http_serv.serve_forever()35 36 Python代码
代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4<meta charset="UTF-8"> 5<title>Title</title> 6 </head> 7 <body> 8 <p>发送消息:<input type="text" id="msg"></p> 9 <button οnclick="send_msg()">发送</button>10 <div id="chat" style="width: 500px;height: 500px;"></div>11 <script type="text/javascript">12var ws = new WebSocket('ws://192.168.19.34:5000/ws');13ws.onmessage = function (data) {14 var ptag = document.createElement('p');15 ptag.innerText = data.data;16 document.getElementById('chat').appendChild(ptag);17};18 19function send_msg() {20 var msg = document.getElementById('msg').value;21 ws.send(msg)22}23 </script>24 </body>25 </html>26 27 页面
页面