python flask websocket_websocket消息订阅 -- flask + flask-socketIO

flask + websocket消息订阅

Flask-SocketIO使Flask应用程序能够在客户端clients 和服务器server之间实现低延迟的全双工通信。 客户端应用程序可以使用JavaScript,C ++,Java和Swift中的任何SocketIO官方客户端库或任何兼容的客户端来建立到服务器的永久连接。

安装

pip install flask-socketio

flask项目接入步骤

1、flask启动文件中 添加websocket配置

方便个人我直接配置在了启动文件中,大家可以将配置单独提出去,规范代码结构,当前仅做参考。

代码中 # websocket配置内容 .... # websocket

from datetime import timedelta

# websocket配置内容

from flask import Flask, render_template, request

from flask_socketio import SocketIO, emit

# websocket

from flask_script import Manager

from apps import create_cms_app

from apps.model import db

# 配置初始化文件

app = create_cms_app("apps.settings.DevCMSConfig")

app.permanent_session_lifetime = timedelta(minutes=60 * 24)

# websocket配置内容

socketio = SocketIO()

socketio.init_app(app)

name_space = '/io'

@socketio.on('recevice message', namespace=name_space)

def test_message(message):

print('recevice message', message)

# emit('message', {'data': message['data']})

@socketio.on('connect', namespace=name_space)

def connected_msg():

"""客户端连接"""

print('client connected!', request.sid)

socketio.emit('abcde', 'hello', namespace=name_space)

@socketio.on('disconnect', namespace=name_space)

def disconnect_msg():

"""客户端离开"""

print('client disconnected!')

@app.route('/push')

def push_once():

event_name = request.args.get("name")

data = request.args.get("msg")

broadcasted_data = {'data': data}

print("publish msg==>", broadcasted_data)

socketio.emit(event_name, broadcasted_data, broadcast=True, namespace=name_space)

return 'send msg successful!'

# websocket

@app.route('/monitor')

def monitor():

"""加载接收消息页面"""

return render_template('monitor.html')

if __name__ == '__main__':

socketio.run(app)

2、前端数据接收 monitor.html

Socket Demo

content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>

$(document).ready(function () {

namespace = '/io';

var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);

socket.on('message', function (res) {

console.log(res.data)

var t = res.data;

if (t) {

{#$("#t").append(t).append('
');#}

$("#monit").html(t);

}

});

socket.on('message2', function (res) {

console.log(res.data)

var t = res.data;

if (t) {

{#$("#t").append(t).append('
');#}

$("#monit1").html(t);

}

});

});

3、Python脚本接入-- 模拟消息推送

import requests, time, random

from multiprocessing import Process

def push_msg(msg, name):

html = requests.get("http://127.0.0.1:5000/push?msg=%s&name=%s" % (msg, name))

print(html.text)

if __name__ == '__main__':

# 模拟推送多条消息

re = []

re2 = []

for i in range(1, 100):

p1 = Process(target=push_msg, args=('--------------' + str(i), 'message'))

re.append(p1)

for i in range(1, 100):

p2 = Process(target=push_msg, args=('--------------' + str(i), 'message2'))

re2.append(p2)

e = re + re2

random.shuffle(e)

for i in e:

time.sleep(1)

i.start()

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