Question

I want to use redis for my game's leaderboard data and I have seen in one of the Stackoverflow questions that txredis is a good option for this. However I cannot find any example which may lead me to start writing some codes. Can anybody help me? Do you know any website having examples? I would appreciate your help.

I am trying to do something like that , however it is not working. TCP Client connects but when it sends "i:xxx" it is disconnected immediately:

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()`
Was it helpful?

Solution

  1. Google for "txredis"
  2. Click on the first link, the txredis project on github
  3. Click on the first entry in the source browser, "examples"
  4. Click on the first entry in the source browser, "demo.py"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top