基于Flask的websocket实现,及群聊、单聊功能开发
一、基于websocket实现通信
后端代码.py文件:
from flask import Flask, request from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from geventwebsocket.websocket import WebSocket app = Flask(__name__) @app.route('/ws_addr') def ws_app(): user_socket=request.environ.get('wsgi.websocket')#type: WebSocket while True: msg=user_socket.receive() user_socket.send(msg) # print(request.environ) # return '访问成功' # ws请求中有而http请求request中没有的差异项[{'HTTP_PRAGMA': 'no-cache'}, {'HTTP_UPGRADE': 'websocket'}, {'HTTP_ORIGIN': 'http://localhost:63342'}, {'HTTP_SEC_WEBSOCKET_VERSION': '13'}, {'HTTP_SEC_WEBSOCKET_KEY': 'G63gzcAOWgjOsoWrsHxIXw=='}, {'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits'}, {'wsgi.websocket_version': '13'}, {'wsgi.websocket': '<geventwebsocket.websocket.WebSocket object at 0x000000000374BC78>'}] if __name__ == "__main__": http_serv = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler) http_serv.serve_forever()
静态文件代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket客户端</title> </head> <body> </body> <script> var ws= new WebSocket("ws://192.168.11.71:9527/ws_addr") ws.onmessage=function (messageevent) { console.log(messageevent.data) } </script> </html>
二、群聊功能实现:
server端代码.py文件:
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__) user_socket_dict = [] @app.route('/ws_addr') def ws_app(): user_socket = request.environ.get('wsgi.websocket') # type: WebSocket user_socket_dict.append(user_socket) while True: msg=user_socket.receive() for usocket in user_socket_dict: usocket.send(msg) @app.route('/') def chat_index(): return render_template("ws_client.html") if __name__ == "__main__": http_serv = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler) http_serv.serve_forever()
配套的静态文件代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket客户端</title> </head> <body> <p> 发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str"> <button id="send_btn" onclick="send()">发送消息</button> </p> <p> <div id="chat_list"> </div> </p> </body> <script> var ws = new WebSocket("ws://192.168.11.71:9527/ws_addr"); ws.onmessage = function (messageevent) { console.log(messageevent.data); var ptag = document.createElement('p'); ptag.innerText = messageevent.data; document.getElementById("chat_list").appendChild(ptag); }; function send() { var msg = document.getElementById('send_str').value; ws.send(msg) } </script> </html>
三、单聊功能实现
server端代码.py文件:
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__) user_socket_dict = {} @app.route('/ws_addr/<user_nick>') def ws_app(user_nick): user_socket = request.environ.get('wsgi.websocket') # type: WebSocket user_socket_dict[user_nick]=user_socket while True: msg=user_socket.receive() print(msg) msg_dict=json.loads(msg) to_user=msg_dict.get('to_user') to_user_socket=user_socket_dict.get(to_user) to_user_socket.send(msg) # ws请求中有而http请求request中没有的差异项[{'HTTP_PRAGMA': 'no-cache'}, {'HTTP_UPGRADE': 'websocket'}, {'HTTP_ORIGIN': 'http://localhost:63342'}, {'HTTP_SEC_WEBSOCKET_VERSION': '13'}, {'HTTP_SEC_WEBSOCKET_KEY': 'G63gzcAOWgjOsoWrsHxIXw=='}, {'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits'}, {'wsgi.websocket_version': '13'}, {'wsgi.websocket': '<geventwebsocket.websocket.WebSocket object at 0x000000000374BC78>'}] @app.route('/') def chat_index(): return render_template("ws_client.html") if __name__ == "__main__": http_serv = WSGIServer(('0.0.0.0', 9527), app, handler_class=WebSocketHandler) http_serv.serve_forever()
配套的静态文件代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket客户端</title> </head> <body> <p> <input type="text" id="nick"> <button onclick="login()">登陆聊天室</button> </p> <p> 发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str"> <button id="send_btn" onclick="send()">发送消息</button> </p> <p> <div id="chat_list"> </div> </p> </body> <script> var ws = null; function login() { nickname = document.getElementById('nick').value; ws = new WebSocket("ws://192.168.11.89:9527/ws_addr/" + nickname); ws.onmessage = function (messageevent) { console.log(messageevent.data); var ptag = document.createElement('p'); var message=JSON.parse(messageevent.data); ptag.innerText = message.from_user+':'+message.message; document.getElementById("chat_list").appendChild(ptag); }; } function send() { var msg = document.getElementById('send_str').value; send_str={ to_user:document.getElementById('to_user').value, from_user:document.getElementById('nick').value, message:msg }; json_send_str=JSON.stringify(send_str); ws.send(json_send_str) } </script> </html>