我有一个独立的 python 脚本,它只是从 Twitter 的流 API 捕获数据,然后在收到每条消息时,使用 redis pubsub 将其发布到频道“tweets”。这是该脚本:
def main():
username = "username"
password = "password"
track_list = ["apple", "microsoft", "google"]
with tweetstream.FilterStream(username, password, track=track_list) as stream:
for tweet in stream:
text = tweet["text"]
user = tweet["user"]["screen_name"]
message = {"text": text, "user": user}
db.publish("tweets", message)
if __name__ == '__main__':
try:
print "Started..."
main()
except KeyboardInterrupt:
print '\nGoodbye!'
我的服务器端 socket.io 实现是使用 django-socketio (基于 gevent-socketio )完成的https://github.com/stephenmcd/django-socketio https://github.com/stephenmcd/django-socketio它只是提供了一些辅助装饰器以及一个broadcast_channel 方法。因为它是在 django 中完成的,所以我只是将此代码放入views.py 中,以便导入它们。我的views.py代码:
def index(request):
return render_to_response("twitter_app/index.html", {
}, context_instance=RequestContext(request))
def _listen(socket):
db = redis.Redis(host="localhost", port=6379, db=0)
client = db.pubsub()
client.subscribe("tweets")
tweets = client.listen()
while True:
tweet = tweets.next()
tweet_data = ast.literal_eval(tweet["data"])
message = {"text": tweet_data["text"], "user": tweet_data["user"], "type": "tweet"}
socket.broadcast_channel(message)
@on_subscribe(channel="livestream")
def subscribe(request, socket, context, channel):
g = Greenlet.spawn(_listen, socket)
客户端 socket.io JavaScript 只需连接并订阅“livestream”频道,并捕获该频道收到的任何消息:
var socket = new io.Socket();
socket.connect();
socket.on('connect', function() {
socket.subscribe("livestream");
});
socket.on('message', function(data) {
console.log(data);
});
这段代码的明显问题是,每次打开页面的新用户或浏览器窗口时,都会生成一个新的 _listen 方法,并且为每个用户订阅和广播推文,从而导致客户端收到重复的消息。我的问题是,哪里应该放置 _listen 方法,以便无论客户端数量如何,它都只创建一次?另外,请记住,broadcast_channel 方法是套接字实例的方法。