как запустить код socketio? - PullRequest
       208

как запустить код socketio?

0 голосов
/ 07 августа 2020

Я хотел бы запустить код рядом с socketio. Моя первая попытка была:

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event

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

#turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

def randomNumberGenerator():
    print("Making random numbers")
    while not thread_stop_event.isSet():
        number = round(random()*10, 3)
        myNumberInPython = random()
        dictForSend = {'number':number,'myOwnNumber':myNumberInPython}
        print(number)
        socketio.emit('newnumber', dictForSend, namespace='/test')
        socketio.sleep(0.2)


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    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')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = socketio.start_background_task(randomNumberGenerator)

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


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

Если я запустил приведенный выше код, последняя строка print('more code') будет выполнена только тогда, когда я остановлю socketio с помощью ctrl + c. Есть ли способ запустить socketio и выполнить последнюю строку print('more code')?

Для запуска кода я использую Raspberry Pi 3 Model B, python версия - 3.7.3

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...