栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

flask同时实现http和websocket

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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'})

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1038781.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号