websocket实例
群聊服务端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 from flask import Flask,request,render_template 2 3 from geventwebsocket.handler import WebSocketHandler 4 from gevent.pywsgi import WSGIServer 5 from geventwebsocket.websocket import WebSocket 6 7 app = Flask(__name__) 8 9 user_socket_list = [] 10 11 @app.route("/conn_ws") 12 def ws_app(): 13 # print(request.environ) 14 """ 15 {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-20180312LANS', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '192.168.11.133', 'REMOTE_PORT': '53449', 'HTTP_HOST': '192.168.11.133:9527', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003B36C48>, 'wsgi.input_terminated': True, 'werkzeug.request': <Request 'http://192.168.11.133:9527/conn_ws' [GET]>} 16 {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-20180312LANS', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '53571', 'HTTP_HOST': '127.0.0.1:9527', 'HTTP_CONNECTION': 'Upgrade', 'HTTP_PRAGMA': 'no-cache', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_UPGRADE': 'websocket', 'HTTP_ORIGIN': 'http://localhost:63342', 'HTTP_SEC_WEBSOCKET_VERSION': '13', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7', 'HTTP_SEC_WEBSOCKET_KEY': 'ET/SDQc1sI+uhxm+EjHLcw==', 'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003BC9468>, 'wsgi.input_terminated': True, 'wsgi.websocket_version': '13', 17 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x0000000003BC8528>, 18 'werkzeug.request': <Request 'http://127.0.0.1:9527/conn_ws' [GET]>} 19 20 """ 21 user_socket = request.environ.get("wsgi.websocket") # type:WebSocket 22 user_socket_list.append(user_socket) 23 print(len(user_socket_list),user_socket_list) 24 25 while True: 26 msg = user_socket.receive() 27 print(msg) 28 29 for usocket in user_socket_list: 30 usocket.send(msg) 31 32 # user_socket.send(msg) 33 34 # 1 已经开启的websocket连接 35 # 3 开启了websocket连接 然后 断开了 36 37 38 # return "666" 39 40 41 @app.route("/") 42 def index(): 43 return render_template("my_ws.html") 44 45 46 if __name__ == '__main__': 47 # app.run() 48 http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) 49 http_serv.serve_forever()
群聊客户端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 </head> 8 <body> 9 <input type="text" id="send_str"> 10 <button id="send_btn" onclick="send()">发送消息</button> 11 <p> 12 <div id="chat_list"> 13 14 </div> 15 </p> 16 </body> 17 <script type="application/javascript"> 18 var ws = new WebSocket("ws://192.168.11.133:9527/conn_ws"); 19 ws.onmessage = function (messageEvent) { 20 console.log(messageEvent.data); 21 var ptag = document.createElement("p"); 22 ptag.innerText = messageEvent.data; 23 document.getElementById("chat_list").appendChild(ptag); 24 }; 25 26 // document.getElementById("send_btn").addEventListener("onclick",) 27 function send() { 28 var send_str = document.getElementById("send_str").value; 29 ws.send(send_str); 30 } 31 </script> 32 </html>
单聊服务端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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("/conn_ws/<user_nick>") def ws_app(user_nick): # print(request.environ) """ {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-20180312LANS', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '192.168.11.133', 'REMOTE_PORT': '53449', 'HTTP_HOST': '192.168.11.133:9527', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT_LANGUAGE': 'zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003B36C48>, 'wsgi.input_terminated': True, 'werkzeug.request': <Request 'http://192.168.11.133:9527/conn_ws' [GET]>} {'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_SOFTWARE': 'gevent/1.4 Python/3.6', 'SCRIPT_NAME': '', 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': False, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'SERVER_NAME': 'PC-20180312LANS', 'SERVER_PORT': '9527', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/conn_ws', 'QUERY_STRING': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '53571', 'HTTP_HOST': '127.0.0.1:9527', 'HTTP_CONNECTION': 'Upgrade', 'HTTP_PRAGMA': 'no-cache', 'HTTP_CACHE_CONTROL': 'no-cache', 'HTTP_UPGRADE': 'websocket', 'HTTP_ORIGIN': 'http://localhost:63342', 'HTTP_SEC_WEBSOCKET_VERSION': '13', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh,en-US;q=0.9,en;q=0.8,zh-CN;q=0.7', 'HTTP_SEC_WEBSOCKET_KEY': 'ET/SDQc1sI+uhxm+EjHLcw==', 'HTTP_SEC_WEBSOCKET_EXTENSIONS': 'permessage-deflate; client_max_window_bits', 'wsgi.input': <gevent.pywsgi.Input object at 0x0000000003BC9468>, 'wsgi.input_terminated': True, 'wsgi.websocket_version': '13', 'wsgi.websocket': <geventwebsocket.websocket.WebSocket object at 0x0000000003BC8528>, 'werkzeug.request': <Request 'http://127.0.0.1:9527/conn_ws' [GET]>} """ user_socket = request.environ.get("wsgi.websocket") # type:WebSocket user_socket_dict[user_nick] = user_socket print(len(user_socket_dict),list(user_socket_dict.keys())) while True: msg = user_socket.receive() # {from_user:"alexDSB",to_user:"YWB",message:"666"} 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) @app.route("/") def index(): return render_template("my_ws.html") if __name__ == '__main__': # app.run() http_serv = WSGIServer(("0.0.0.0",9527),app,handler_class=WebSocketHandler) http_serv.serve_forever()
单聊客户端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 </head> 8 <body> 9 <p><input type="text" id="nick"><button onclick="login()">登陆聊天室</button></p> 10 发送给:<input type="text" id="to_user">消息:<input type="text" id="send_str"> 11 <button id="send_btn" onclick="send()">发送消息</button> 12 <p> 13 <div id="chat_list"> 14 15 </div> 16 </p> 17 </body> 18 <script type="application/javascript"> 19 var ws = null; 20 function login() { 21 var nick = document.getElementById("nick").value; 22 ws = new WebSocket("ws://192.168.11.133:9527/conn_ws/"+nick); 23 ws.onmessage = function (messageEvent) { 24 console.log(messageEvent.data); 25 var ptag = document.createElement("p"); 26 27 var message = JSON.parse(messageEvent.data); 28 29 ptag.innerText =message.from_user + " : " + message.message ; 30 document.getElementById("chat_list").appendChild(ptag); 31 }; 32 } 33 34 // document.getElementById("send_btn").addEventListener("onclick",) 35 function send() { 36 var message = document.getElementById("send_str").value; 37 var send_str = { 38 from_user:document.getElementById("nick").value, 39 to_user:document.getElementById("to_user").value, 40 message:message 41 }; 42 var json_send_str = JSON.stringify(send_str); 43 ws.send(json_send_str); 44 } 45 </script> 46 </html>