在使用 Websockets 运行我的 Flask 应用程序时,我总是遇到这个错误。 我已尝试遵循本指南 - http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent
我有一个 flask 应用程序,它为我的网络嗅探器提供了 GUI 界面。嗅探器在一个线程内,如下所示:(l 是我的嗅探器的线程;isRunning 是一个 bool 值,用于检查线程是否已经在运行)
try:
if l.isRunning == False: # if the thread has been shut down
l.isRunning = True # change it to true, so it could loop again
running = True
l.start() # starts the forever loop / declared from the top to be a global variable
print str(running)
else:
running = True
print str(running)
l.start()
except Exception, e:
raise e
return flask.render_template('test.html', running=running) #goes to the test.html page
嗅探器在没有 socketio 的情况下运行良好,我能够在遍历我的 gui 时嗅探网络。但是,当我在代码中包含 socketio 时,我首先看到 socketio 在我的索引页面中工作并且我能够接收从服务器到页面的消息。我也可以很好地遍历我的 GUI 中的其他静态页面;但是,激活我的线程网络嗅探器会使我的浏览器挂起。我总是收到 Exception gevent.hub.LoopExit: LoopExit('This operation would block forever',) 错误,当我重新运行我的程序时,控制台会说该地址已在使用中。在我看来,发生这种情况时我可能没有正确关闭套接字。我还认为某些操作是基于错误而阻塞的。我的 python flask 应用程序中的代码如下所示
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
time.sleep(10)
count += 1
socketio.emit('my response',{'data': 'Server generated event', 'count': count},namespace='/test')
if socketflag is None:
thread = Thread(target=background_thread)
thread.start()
@socketio.on('my event', namespace='/test')
def test_message(message):
emit('my response', {'data': message['data']})
@socketio.on('my broadcast event', namespace='/test')
def test_message(message):
emit('my response', {'data': message['data']}, broadcast=True)
@socketio.on('connect', namespace='/test')
def test_connect():
emit('my response', {'data': 'Connected'})
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
这是我的索引页面中的代码。
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = '/test'; // change to an empty string to use the global namespace
// the socket.io documentation recommends sending an explicit package upon connection
// this is specially important when using the global namespace
var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function () {
socket.emit('my event', {data: 'I\'m connected!'});
});
// event handler for server sent data
// the data is displayed in the "Received" section of the page
socket.on('my response', function (msg) {
$('#log').append('<br>Received #' + msg.count + ': ' + msg.data);
});
});
</script>
最佳答案
我不久前遇到了这个问题,这是由于没有正确地对 threading
模块进行猴子修补造成的。
在您的应用顶部,应用 gevent 补丁:
from gevent import monkey, sleep
monkey.patch_all()
关于python - 异常 gevent.hub.LoopExit : LoopExit ('This operation would block forever' , ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29320160/