使用socketIO将数据从python Queue()传递到烧瓶

时间:2019-10-05 15:34:41

标签: python multithreading flask subprocess flask-socketio

我正在尝试使用socketIO将Queue对象中的项目传递到烧瓶中。console.log中的输出不是“ not”,而在终端中我将队列项目作为output.SocketIo无法将队列项目发送给客户端。 这只是测试代码。我使用的是来自github的网络入侵数据集创建者的代码,这里是链接。https://github.com/nrajasin/Network-intrusion-dataset-creator/blob/master/counts.py在代码269行,我添加了web.put(set.Dataset),类似于下面的代码,但是问题是socket.emit是无法回应客户。

counts.py

from queue import *
global web
web = Queue()
Data = {"item1":"apple","item2":"mango"}
web.put(Data)

app.py

import counts
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event
import set

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

socketio = SocketIO(app)

thread = Thread()
thread_stop_event = Event()

class Random(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomGenerator(self):
        while not thread_stop_event.isSet():
            if counts.web.empty()==False:
                Data = counts.web.get()
                print(Data)
            else:
                Data = "not"
                print(Data)
            socketio.emit('newnumber', {'number': Data}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomGenerator()

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)


端子输出

{'item1': 'apple', 'item2': 'mango'}
not
not
not
not
not
not
{'item1': 'apple', 'item2': 'mango'}
not
not
{'item1': 'apple', 'item2': 'mango'}

console.log()输出

not
not
not

0 个答案:

没有答案