当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Flask websocker

Flask websocker

2019年12月10日  | 移动技术网IT编程  | 我要评论

群聊版

安装

pip install gevent-websocket  

 

视图

  1. # -*- coding: utf-8 -*-  
  2. import json  
  3. from flask import flask, request, render_template  
  4. from geventwebsocket.handler import websockethandler  # 导入websocker的方法  
  5. from gevent.pywsgi import wsgiserver  
  6.     
  7. app = flask(__name__)  
  8.     
  9. user_socker_list = []  # 保存所有的websocker对象  
  10.     
  11. @app.route('/ws')  
  12. def ws():  
  13.     # print(request.headers)  
  14.     user_socker = request.environ.get('wsgi.websocket')  # type  websocket  
  15.     
  16.     """  
  17.     readystate: 3  连接正常,然后断开  
  18.     readystate: 1  表示正常连接  
  19.     """  
  20.     if user_socker:  
  21.         user_socker_list.append(user_socker)  
  22.         while 1:  
  23.             msg = user_socker.receive()  # 接收消息  
  24.             print(msg)  # 接受完信息后断开,所有加循环变成长连接  
  25.             for u_socker in user_socker_list:  
  26.                 if u_socker == user_socker:  
  27.                     continue  
  28.                 try:  
  29.                     u_socker.send(msg)  
  30.                 except:  
  31.                     continue  
  32.     
  33.     return render_template('ws.html')  
  34.     
  35.     
  36. if __name__ == '__main__':  
  37.     # app.run(host='0.0.0.'debug=true)  
  38.     http_serv = wsgiserver(('0.0.0.0', 5000), app, handler_class=websockethandler)  
  39.     http_serv.serve_forever()  

 

前端

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>ws</title>  
  6. </head>  
  7. <body>  
  8. <input type="text" id="msg"> <button onclick="snd_msm()">发送</button>  
  9.     
  10. <div id="chat_list" style="width: 500px; height: 500px;">  
  11.     
  12. </div>  
  13.     
  14. </body>  
  15.     
  16. <script type="application/javascript">  
  17.     var ws = new websocket('ws://192.168.32.71:5000/ws');  {# 设置websocker连接 #}  
  18.     ws.onmessage = function (data) {  
  19.         console.log(data.data);  {# 数据在datadata里面 #}  
  20.         var ptag = document.createelement('p');  
  21.         ptag.innertext = data.data;  
  22.         document.getelementbyid('chat_list').appendchild(ptag)  
  23.     
  24.     }; {# 打印收到的数据 #}  
  25.         
  26.     function snd_msm() {  
  27.         var msg = document.getelementbyid('msg').value;  
  28.         ws.send(msg)  
  29.     }  
  30. </script>  
  31. </html>  

 

一对一单机版

视图

  1. # -*- coding: utf-8 -*-  
  2. import json  
  3. from flask import flask, request, render_template  
  4. from geventwebsocket.handler import websockethandler  # 导入websocker的方法  
  5. from gevent.pywsgi import wsgiserver  
  6.     
  7. app = flask(__name__)  
  8.     
  9. user_socker_dict = {}  # 这里仿照flask上下文的方式  
  10.     
  11. """  
  12. 借用  
  13. flask 上下文  
  14.     
  15. {  
  16. "线程id": 偏函数,  
  17. "线程id": 偏函数,  
  18. }  
  19. """  
  20.     
  21. @app.route('/ws2/<usename>')  
  22. def ws2(usename):  
  23.     # print(request.headers)  
  24.     user_socker = request.environ.get('wsgi.websocket')  # type  websocket  
  25.     
  26.     """  
  27.     readystate: 3  连接正常,然后断开  
  28.     readystate: 1  表示正常连接  
  29.     """  
  30.     print(user_socker)  
  31.     if user_socker:  
  32.         user_socker_dict[usename] = user_socker  
  33.         print(user_socker_dict)  
  34.         while 1:  
  35.             msg = user_socker.receive()  # 接收人,消息,发送人  
  36.             msg_dict = json.loads(msg)  
  37.             msg_dict['from_user'] = usename  
  38.             to_user = msg_dict.get('to_user')  
  39.             u_socker = user_socker_dict.get(to_user)  # type  websocket  
  40.             u_socker.send(json.dumps(msg_dict))  
  41.     
  42.     return render_template('ws2.html')  
  43.     
  44.     
  45. if __name__ == '__main__':  
  46.     # app.run(host='0.0.0.'debug=true)  
  47.     http_serv = wsgiserver(('0.0.0.0', 5000), app, handler_class=websockethandler)  
  48.     http_serv.serve_forever()  

 

前端

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <title>ws</title>  
  6. </head>  
  7. <body>  
  8. <input type="text" id="username"> <button onclick="login()">登陆聊天室</button>  
  9.     
  10. <input type="text" id="to_user">发送:<input type="text" id="msg"> <button onclick="snd_msm()">发送</button>  
  11.     
  12. <div id="chat_list" style="width: 500px; height: 500px;">  
  13.     
  14. </div>  
  15.     
  16. </body>  
  17.     
  18. <script type="application/javascript">  
  19.     var ws = null;  {# 为什么设置null, 被其他函数执行 #}  
  20.     
  21.     function login() {  
  22.         var username = document.getelementbyid('username').value;  
  23.         ws = new websocket('ws://192.168.32.71:5000/ws2/' + username);  {# 设置websocker连接 #}  
  24.         ws.onmessage = function (data) {  
  25.             var recv_msg = json.parse(data.data);  
  26.             var ptag = document.createelement('p');  
  27.             ptag.innertext = recv_msg.from_user + ":" + recv_msg.msg;  
  28.             document.getelementbyid('chat_list').appendchild(ptag)  
  29.         }; {# 打印收到的数据 #}  
  30.     
  31.     }  
  32.     
  33.     function snd_msm() {  
  34.         var to_user = document.getelementbyid('to_user').value;  
  35.         var msg = document.getelementbyid('msg').value;  
  36.         send_msg = {  
  37.             "to_user" : to_user,  
  38.             "msg": msg  
  39.         };  
  40.         ws.send(json.stringify(send_msg));  
  41.     }  
  42. </script>  
  43. </html>  

 

websocker

视图

  1. import time  
  2. from django.shortcuts import render  
  3. from dwebsocket.decorators import accept_websocket  
  4.     
  5.     
  6. @accept_websocket  
  7. def test(request):  
  8.     if request.is_websocket():  
  9.         print('websocket connection....')  
  10.         msg = request.websocket.wait()  # 接收前端发来的消息  
  11.         print(msg, type(msg), json.loads(msg))  # b'["1","2","3"]' <class 'bytes'> ['1', '2', '3']  
  12.         while 1:  
  13.             if msg:  
  14.                 # 你要返回的结果  
  15.                 for i in range(10):  
  16.                     request.websocket.send(str(i).encode())  # 向客户端发送数据  
  17.                 request.websocket.close()  
  18.     else:  # 如果是普通的请求返回页面  
  19.         return render(request, 'test.html')  

前端

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8">  
  5.     <meta http-equiv="x-ua-compatible" content="ie=edge">  
  6.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.     <title>test</title>  
  8. </head>  
  9. <body>  
  10. <div></div>  
  11.     
  12. </body>  
  13. <input type="text" id="message" value="hello, world!"/>  
  14. <button type="button" id="send_message">发送 message</button>  
  15.     
  16. <!-- 首先引入 jquery -->  
  17. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>  
  18. <script>  
  19.     // 判断浏览器是否支持websocket,目前应该所有的浏览器都支持了.....  
  20.     if ('websocket' in window) {  
  21.         console.log('你的浏览器支持 websocket')  
  22.     }  
  23.     $('#send_message').click(function () {  
  24.         // 创建一个websocket对象:sk,并且建立与服务端的连接(服务端程序要跑着哦)  
  25.         var sk = new websocket('ws://' + window.location.host + '/asset/test/');  
  26.         // 向服务端发送消息  
  27.         sk.onopen = function () {  
  28.             console.log('websocket connection successful...');  
  29.             var datas = $('#message').val();  
  30.             sk.send(json.stringify(datas));  
  31.         };  
  32.         // 接收服务端的消息,主要的业务逻辑也在这里完成  
  33.         sk.onmessage = function (msg) {  
  34.             // 业务逻辑  
  35.             html = "<p>" + msg.data + "</p>";  
  36.             $("div").append(html);  
  37.             console.log('from service message: ', msg.data);  
  38.             // 由于服务端主动断开连接,这里也断开websocket连接  
  39.             if (sk.readystate == websocket.closed) sk.close();  
  40.         };  
  41.         // 完事就关闭websocket连接  
  42.         sk.onclose = function (msg) {  
  43.             console.log('websocket connection close...');  
  44.             sk.close()  
  45.         };  
  46.         // websocket连接创建成功后,我们就可以向服务端发送数据了  
  47.         if (sk.readystate == websocket.open) sk.onopen();  
  48.     
  49.     });  
  50.     
  51. </script>  
  52. </html>  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网