Flask websocker

Posted 小白森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask websocker相关的知识,希望对你有一定的参考价值。

群聊版

安装

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>??

以上是关于Flask websocker的主要内容,如果未能解决你的问题,请参考以下文章

python Flask - 数据库片段

Flask 编写http接口api及接口自动化测试

12_关于flask中的宏

java代码编辑器 pdf文件预览 主流SSM 代码生成器 shrio redis websocke

Flask之模板之宏继承包含

Flask模板宏的概念和基本使用