flask同时实现http和websocket

两种协议在一个工程中实现

服务端

from flask import Flask, Response
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)


@socketio.on('server')
def endpoint_socket(data):
    print(f'客户端发送来的消息:{data}')
    emit('client', {'message': 'I am server'})


@app.route("/http/", methods=["GET", "POST"])
def endpoint_http():
    print('调用http')
    return Response('I am server')


socketio.run(app, host="0.0.0.0", port=8000, debug=True)

通过flask_socketio提供的SocketIO封装flask的app实现了websocket,同时不影响flask的http接口。

客户端

import time

import socketio

num = 1

sio = socketio.Client()


@sio.on('client')
def on_message(data):
    global num
    print(f'第{num}次发送')
    num += 1
    time.sleep(1)
    print('client received a message!', data)
    sio.emit('server', {'message': 'who are you', 'session_id': ''})


@sio.event
def connect_error(info):
    print(f"The connection failed: {info}")


@sio.event
def disconnect():
    print('disconnected from server')


sio.connect('http://localhost:8000')
sio.emit('server', {'message': 'I am client'})

flask同时实现http和websocket_第1张图片

你可能感兴趣的:(开发,flask,http,websocket)