Search code examples
pythontwisted

Python Twisted: What Is Received with DataReceived and What Should I Probably Use Instead


I'm tooling around with a text-based adventure game in Python with Twisted and I think I've fundamentally misunderstood what comes back with Twisted's dataReceived function. I've got the following as part of my overall code;

def process(self, data):
    print "Got command {}, {}".format(data, len(data))
    if data == "test":
        print "DEBUG: got the test command"


from twisted.internet import reactor, protocol

class MudLoop(protocol.Protocol):

  def connectionMade(self):
    login(self)

  def dataReceived(self, data):
    process(self, data)


factory = protocol.ServerFactory()
factory.protocol = MudLoop
reactor.listenTCP(12000,factory)
reactor.run()

No string sent back from dataReceived will trigger the process function's test for it and do something else, e.g. if a connected client enters 'test', no console output is received as per the DEBUG instruction saying it got the test command. I've got a couple of theories as to why, the first is that what's being passed isn't a string, the second is that while it's a string it's got invisible characters (carriage return and new line?) appended to it that are making it fail the test for what was entered - this seems supported by my test for the process function being called adding the length of the command in the console on a new line.

Which of these are true? Or is it something else? And in any case should I be testing the string returned from dataReceived in this way? Researching before I posted seems to suggest that other people haven't had this problem but do run into other problems later with strings receiving in an indeterminate order from multiple clients. If I solve this is my approach wrong and I'm just going onto the next problem as a result?


Solution

  • This is a Twisted FAQ: Why is dataReceived called with only part of the data I called transport.write with?.