El desarrollo real de matraz: cómo configurar el matraz y nginx para admitir websocket

El uso de pycharm para iniciar el proyecto del matraz tiene dificultades, primero modifique la configuración de pycharm

1. Haga clic en Editar configuraciones

2. Configurar el método de inicio

1 Agregue una nueva configuración de inicio
2 Elija usar el comando python para ejecutar
3 Establezca un nombre para la configuración
4 Establezca la ubicación del módulo que se iniciará, el matraz es básicamente el módulo app.py

Finalmente, no olvide: haga clic en aplicar a la derecha

1. matraz

1.1, la configuración del marco de matraz admite websocket

Paquete de dependencia:

pip install vent-websocket==0.10.1
pip install vent==21.1.2
pip install vent==1.1.2

1. Método de configuración 1: use gevent-websocket y gevent para implementar juntos

import time
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
from flask import Flask, request

app = Flask(__name__)

@app.route('/ws')
def ws():
    socke = request.environ.get('wsgi.websocket')
    while True:
        msg = socke.receive()
        print('客户端发送的信息:', msg)
        if msg == None:
            print('客户端结束websocket连接')
            break
        socke.send(f'接收到的时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
    return 'ok'

if __name__ == '__main__':
    # 使用WSGIServer使用项目支持sse,支持websocket
    ser = WSGIServer(('0.0.0.0', 8888), app, handler_class=WebSocketHandler)
    ser.serve_forever()

2. Configuración 2: use solo el paquete gevent-websocket

import time
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket.server import WSGIServer
from geventwebsocket.websocket import WebSocket #语法提示
from flask import Flask
from flask import request
import time
print('flask启动...')
app = Flask(__name__)

@app.route('/ws')
def ws():
    sock = request.environ.get('wsgi.websocket')
    print(sock)
    while True:
        msg = sock.receive()
        print(msg,'接收到的数据')
        if msg==None:
            break
        sock.send(f'收到数据的时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
    return 'ok'

if __name__ == '__main__':
    #使用WSGIServer使用项目支持sse,支持websocket
    ser = WSGIServer(('0.0.0.0',8888),app,handler_class=WebSocketHandler)
    ser.serve_forever()

1.2 Iniciar websocket a través de un script de python

Paquete de dependencia:

pip3 instalar websocket-cliente

Cuando nginx está configurado con un certificado y usa el protocolo https, use wss://nombre de dominio:443/api/ws 

from websocket import create_connection
import websocket

def main():
    #ambulance.thearay.net:443
    url = 'wss://ambulance.jinho.net:443/api/websocket/ws'
    ws = create_connection(url)
    print("获取连接状态:", ws.connected)
    while True:
        send_data = input('>>>>>>>>')
        print(f'send >>> {send_data}')
        ws.send(f"{send_data.strip()}")
        response = ws.recv()
        print("recv >>> ", response)
        if response =='close':
            break
    ws.close()

if __name__ == '__main__':
    main()

Cuando nginx no está configurado con un certificado y usa el protocolo http, use ws://nombre de dominio:80/api/ws

from websocket import create_connection
def main():
    url = 'ws:/ambulance.jinho.net:80/api/ws'
    ws = create_connection(url)
    print("获取连接状态:", ws.connected)
    while True:
        data = input('发送数据>>>>')
        ws.send(data)
        response = ws.recv()
        print("接收数据>>>>", response)
        if response=='close':
            ws.close()
if __name__ == '__main__':
    main()

dos, nginx

Lo más importante es configurar los siguientes tres en la configuración de la solicitud de matraz de proxy

 ubicación /api/{

         proxy_pass http://127.0.0.1:8888/api/;

         proxy_http_versión 1.1;
         proxy_set_header Actualizar $http_upgrade;
         proxy_set_header Conexión "actualizar";

}

configuración https

 server {
    	listen 443 ssl;
	    server_name 127.0.0.1;
    	ssl_certificate cert/8386707_ambulance.jinho.net.pem;
    	ssl_certificate_key cert/8386707_ambulance.jinho.net.key;
   	    ssl_session_timeout 5m;
    	ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    	ssl_prefer_server_ciphers on;
    	client_max_body_size 10m;


	    location  /static  {
		    alias  C:/5G/5GApi/static; 
		}

	    location / {
		    root   C:\\5G\\nginx-1.17.8\\dist; #默认访问目录
            index  index.html;
		    # try_files $uri $uri/ /index.html;
		}

	    location /api/ {
		       #后端
		  
		       proxy_pass http://127.0.0.1:8888/;
		       proxy_buffering off; #nginx实现sse的功能,不配置就无法实现sse功能

		       #nginx配置支持websocket,下面三条
    	       proxy_http_version 1.1;
    	       proxy_set_header Upgrade $http_upgrade;
   	 	       proxy_set_header Connection "upgrade";
		   
               #websocket的超时处理
		       proxy_read_timeout 600s;
               proxy_connect_timeout 30s;
               proxy_send_timeout 60s;
		  }
	
#server的括号
    }

Ir al protocolo http

 server {
    	listen 80;
	    server_name 127.0.0.1;
    	client_max_body_size 10m;
        root html;
        index index.html index.htm;

	    location  /static  {
		    alias  C:/5G/5GApi/static; 
		}

	    location / {
		    root   C:\\5G\\nginx-1.17.8\\dist; #默认访问目录
            index  index.html;
		    # try_files $uri $uri/ /index.html;
		}

	    location /api/ {
		       #后端
		  
		       proxy_pass http://127.0.0.1:8888/;
		       proxy_buffering off; #nginx实现sse的功能,不配置就无法实现sse功能

		       #nginx配置支持websocket,下面三条
    	       proxy_http_version 1.1;
    	       proxy_set_header Upgrade $http_upgrade;
   	 	       proxy_set_header Connection "upgrade";
		   
               #websocket的超时处理
		       proxy_read_timeout 600s; #两次请求之前不能超过600s,自动关闭连接的元凶
               proxy_connect_timeout 30s; #创建连接时60s超时
               proxy_send_timeout 60s;    #服务的发送数据时,60s超时

		  }

    }

4. Puedes probar el sitio web

Herramienta de prueba en línea EasySwoole-WebSocket

Supongo que te gusta

Origin blog.csdn.net/weixin_46371752/article/details/130258238
Recomendado
Clasificación