python flask实现websocket

flask项目实现websocket

1.from flask_socketio import SocketIO
2.app = Flask(__name__)
3.socketio = SocketIO(app)
4.启动flask项目时候要用如下方式启动
   socketio.run(app, host='', port=)
5.在启动项目的同一文件下,添加如下代码
WS = []
@socketio.on('connect' ,namespace = '/websocket')
def connect_socket(ws):
    global WS
    while not ws.closed:
        try:
            WS.append(ws)
            str_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            message = ws.receive()
            ws.send("time:%s,msg: %s"%(str_time,str(message)))
        except Exception as e:
            print('error:',e)
6.nginx配置文件需要加入如下内容:
        location /webSocket {
            root /home/ka/ui;
            include proxy_params;
            proxy_http_version 1.1;
            proxy_buffering off;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass http://127.0.0.1:4000/webSocket;
        }
7.前端也要配合修改内容如下:
function websocket() {
    var websocket = null;
    var isRefresh=false;
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("wss://"+window.location.host+"/webSocket");
    } else{
        console.log('Not support websocket')
    }
    //连接发生错误的回调方法
    websocket.onerror = function(){
        console.log('error')
    };
    //连接成功建立的回调方法
    websocket.onopen = function(event){
        console.log('open')
    };
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        websocket.send('1111');
    };
    //连接关闭的回调方法
    websocket.onclose = function(e){
        if(isRefresh){
            isRefresh=false;
            return;
        }
        console.log("close");
        console.log(e);
        // window.location.replace(APPCONFIG["default"].LOGIN_URL);
    };
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        isRefresh=true;
        websocket.close();
    }
}


你可能感兴趣的:(websocket,python,flask)