如何使用txredis为客户端服务器通信编写异步扭曲的应用程序

时间:2012-01-19 22:24:40

标签: redis twisted factory reactor

我想将 redis 用于我的游戏排行榜数据,我在其中一个Stackoverflow问题中看到 txredis 是一个不错的选择。但是我找不到任何可能导致我开始编写代码的例子。有谁能够帮我?你知道任何网站有例子吗?我很感激你的帮助。

我正在尝试做类似的事情,但它不起作用。 TCP客户端连接但是当它发送“i:xxx”时它会立即断开连接:

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor
from twisted.internet import defer
from txredis.protocol import Redis
from twisted.internet import protocol

# Hostname and Port number of a redis server
HOST = 'localhost'
PORT = 6379

@defer.inlineCallbacks


def main():
    clientCreator = protocol.ClientCreator(reactor, Redis)
    redis = yield clientCreator.connectTCP(HOST, PORT)    
    res = yield redis.ping()
    print res

    info = yield redis.info()
    print info

    res = yield redis.set('test', 42)
    print res

    test = yield redis.get('test')
    print test



class LeaderBoard(Protocol):
        def connectionMade(self):
            self.factory.clients.append(self)
        clientCreator = protocol.ClientCreator(reactor, Redis)
        redis = yield clientCreator.connectTCP(HOST, PORT)
    def connectionLost(self, reason):
        print "client removed",self
        self.factory.clients.remove(self)
    def dataReceived(self, data):
        defer.inlineCallbacks
        a = data.split(':')
        if len(a) > 1:
            command = a[0]
            content = a[1]

            res = yield self.redis.set('test', 42)
            print res            

            msg = ""
            score = ""

            if command == "i":
                self.name = content
                msg = self.name + " has joined"

                print msg
            elif command== "msg":
                msg = self.name + ": " + content
                self.message(msg)
    def message(self, message):
        self.transport.write(message + '\n')

if __name__ == "__main__":

    factory = Factory()

    factory.protocol = LeaderBoard
    factory.clients = []

    reactor.listenTCP(80, factory)
    print "Iphone Chat server started"
    reactor.run()`

1 个答案:

答案 0 :(得分:0)

  1. Google for“txredis”
  2. 点击第一个链接,即github上的txredis项目
  3. 点击源浏览器中的第一个条目“examples”
  4. 点击源浏览器中的第一个条目“demo.py”