我有Python服务器代码fserver.py,在连接时我试图创建线程,一旦线程创建并运行,我试图在每秒之后将计数器值增加1,并将事件发送回连接客户端以显示服务器到客户端之间的增量计数器值
import sys
from threading import Thread, Event
import time
from flask import Flask, jsonify, request, json
from flask_socketio import SocketIO, emit
from flask_cors import CORS
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__)
app.config["SECRET_KEY"] = "secret!"
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)
thread = Thread()
thread_stop_event = Event()
class CounterThread(Thread):
def __init__(self):
self.delay = 0.5
super(CounterThread, self).__init__()
def start_counterthread(self):
print("Initializing Thread==")
try:
counter = 0
while not thread_stop_event.isSet():
counter = counter + 1
time.sleep(1)
print(counter, " counter ")
jsonResp = {"counter": counter}
emit("counter", jsonResp)
time.sleep(self.delay)
except KeyboardInterrupt:
print("Keyboard Interrupt")
def run(self):
self.start_counterthread()
@socketio.on("connect")
def test_connect():
print("Client connected")
global thread
if not thread.isAlive():
print("Starting Thread")
thread = CounterThread()
thread.start()
if __name__ == "__main__":
print("main === 1")
http_server = WSGIServer(('127.0.0.1', 5000), app, handler_class=WebSocketHandler)
print("main === 2")
http_server.serve_forever()
print("main === 3")
和客户端代码
import React, { Component } from 'react'
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:5000/";
export default class Toggle extends Component {
componentDidMount = () => {
// Create WebSocket connection.
const socket = socketIOClient.connect(ENDPOINT, { transports: ['websocket'] });
// socket.on('connect', () => console.log('Test connected!!'));
socket.on("responseMessage", data => {
console.log(data);
});
}
}
我正在尝试获取客户端中的计数数据,该数据每秒钟增加1。
错误如下:
C:\work\Flask> python fserver.py
main === 1
main === 2
Client connected
Starting Thread
Initializing Thread==
1 counter
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\tools\python3\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "fserver.py", line 39, in run
self.start_counterthread()
File "fserver.py", line 33, in start_counterthread
emit("counter", jsonResp)
File "C:\tools\python3\lib\site-packages\flask_socketio\__init__.py", line 772, in emit
namespace = flask.request.namespace
File "C:\tools\python3\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\tools\python3\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\tools\python3\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.