赞
踩
声明:python的服务器建议使用gunicorn,而uwsgi服务器比较复杂,看个人情况来,个人不建议使用,太麻烦,使用uwsgi配置websocket反正我是一直没连通!!!
第一步参考文章:https://www.jianshu.com/p/69e75fc3e08e
Gunicorn是一个unix上被广泛使用的高性能的Python WSGI UNIX HTTP Server。
和大多数的web框架兼容,并具有实现简单,轻量级,高性能等特点。
gunicorn 安装
pip install gunicorn
gunicorn + flask 简单示例
python测试文件:testSockets.py
- from flask import Flask
- from flask_sockets import Sockets
-
-
- app = Flask(__name__)
- sockets = Sockets(app)
-
-
- @sockets.route('/')
- def echo_socket(ws):
- while not ws.closed:
- # 服务器端没关闭之前必须有接收阻塞,否则服务器和客户端都会死循环而崩溃
- # websocket的原理:客户端发送消息请求,服务器端回复数据【客户端不发消息,循环不会阻塞就是死循环】
- message = ws.receive()
- print("监听成功")
- ws.send(message)
-
-
- @app.route('/')
- def hello():
- return 'http请求访问成功'
-
-
- if __name__ == "__main__":
- from gevent import pywsgi
- from geventwebsocket.handler import WebSocketHandler
- server = pywsgi.WSGIServer(('0.0.0.0', 9099), app, handler_class=WebSocketHandler)
- server.serve_forever()

通过gunicorn运行flask app【兼容websocket的运行方式】
- // pip install geventwebsocket【首先必须安装geventwebsocket】
-
- (uniapp-Flask) (base) [root@VM_0_2_centos websocketTest]# gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker --bind 0.0.0.0:9099 testSockets:app
- [2019-07-29 15:57:54 +0800] [8932] [INFO] Starting gunicorn 19.9.0
- [2019-07-29 15:57:54 +0800] [8932] [INFO] Listening at: http://0.0.0.0:9099 (8932)
- [2019-07-29 15:57:54 +0800] [8932] [INFO] Using worker: geventwebsocket.gunicorn.workers.GeventWebSocketWorker
- [2019-07-29 15:57:54 +0800] [8939] [INFO] Booting worker with pid: 8939
测试http请求结果【非nginx的情况】
- # curl http://127.0.0.1:9099
- 'http请求访问成功'
测试websocket请求 【非nginx的情况】
- 测试ws请求
- 测试网站:http://www.blue-zero.com/WebSocket/
-
- ws://ip:9099
- # gunicorn.py服务器的配置文件,更多参数参考官方文档:http://docs.gunicorn.org/en/stable/configure.html
-
- import multiprocessing
-
- bind = "0.0.0.0:8099"
- workers = multiprocessing.cpu_count() * 2 + 1
- chdir="/root/uniapp-Flask"
- backlog = 2048
- worker_class = "geventwebsocket.gunicorn.workers.GeventWebSocketWorker"
- worker_connections = 1000
- daemon = True # 是否开启后台启动【True开启】
- debug = True
-
- # gunicorn -c ../gunicorn.py testSockets:app
- # websocket配置参考官方文档:http://nginx.org/en/docs/http/websocket.html
-
- server {
- listen 80 default_server;
- server_name 0.0.0.0;
-
- location / {
- include uwsgi_params;
- proxy_pass http://119.28.180.116:9099;
- # 下面三个选项是websocket必须的【参考官方文档】
- proxy_http_version 1.1;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection "upgrade";
- }
- }
参考我的这篇文章:https://blog.csdn.net/weixin_43343144/article/details/97660632
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。