我有一个围绕flask-socketIO框架构建的客户端 - 服务器设置。其中一个应用程序是服务器重复轮询数据库,并在更新时让客户端知道。这是我的代码的简单版本:
客户端代码:
function poll(){
socket.emit('pollForUpdates');
}
socket.on("update",function(msg){
alert("Recieved update");
});
服务器端代码:
@socketio.on('pollForUpdates')
def pollForUpdates():
event = threading.Event()
k = ThreadJob(poll, event, 2)
k.start()
class ThreadJob(threading.Thread):
def __init__(self,callback,event,interval):
'''runs the callback function after interval seconds
:param callback: callback function to invoke
:param event: external event for controlling the update operation
:param interval: time in seconds after which are required to fire the callback
:type callback: function
:type interval: int
'''
self.callback = callback
self.event = event
self.interval = interval
super(ThreadJob,self).__init__()
def run(self):
while not self.event.wait(self.interval):
self.callback()
def poll():
print "Polling at {}".format(datetime.now())
socketio.emit("update")
gevent.sleep(0)
客户端无法接收服务器发送的更新。