如何通过gevent的事件实现comet

0 投票
1 回答
890 浏览
提问于 2025-04-17 03:56

这里有一个示例,展示了如何用gevent和flask来实现comet技术。

#coding:utf-8
'''
Created on Aug 6, 2011

@author: Alan Yang
'''
import time
from gevent import monkey
monkey.patch_all()

from gevent.event import Event
from gevent.pywsgi import WSGIServer

from flask import Flask,request,render_template,jsonify

app = Flask('FlaskChat')
app.event = Event()
app.cache = []
app.cache_size = 12

@app.route('/')
def index():
    return render_template('index.html',messages=app.cache)

@app.route('/put',methods=['POST'])
def put_message():
    message = request.form.get('message','')
    app.cache.append('{0} - {1}'.format(time.strftime('%m-%d %X'),message.encode('utf-8')))
    if len(app.cache) >= app.cache_size:
        app.cache = app.cache[-1:-(app.cache_size):-1]
    app.event.set()
    app.event.clear()
    return 'OK'

@app.route('/poll',methods=['POST'])
def poll_message():
    app.event.wait()
    return jsonify(dict(data=[app.cache[-1]]))


if __name__ == '__main__':
    #app.run(debug=True)
    WSGIServer(('0.0.0.0',5000),app,log=None).serve_forever()

这个示例使用了gevent的事件类。如果有人发布了一条消息,聊天室里的所有人都会收到这条消息。

但是如果我只想让某一个人收到这条消息呢?我是不是应该使用gevent.event.AsyncResult?如果是的话,应该怎么做呢?

1 个回答

0

使用 gevent.queue.Queue

从队列中读取信息时,会把这个信息移除。如果有多个读取者,每条信息只会被其中一个读取者接收到(具体是哪个读取者接收到是不确定的,没有随机性或公平性,只是随便的)。

撰写回答