Search code examples
pythonnetwork-programmingtwisted

In twisted how can I make a mixed protocol which returns Lines or Raw based on input?


I am trying to develop a mixed protocol which can return a raw response or a Line Based response based on the request. My code looks like

class Receiver(LineReceiver):
def lineReceived(self, line):
    (command, args) = self._parse_command(line)
    result = self.exec_command(command, args) #Secret sauce returns list or blob.
    if  isinstance(result, basestring): # won't work in 3.0 ; least of my worries.
        self.sendLine(str(len(result))) # Sends no. of bytes as a line.
        self.transport.write(result)   #followed by bytes. This is not received by the client.
        self.transport.loseConnection()
    else:
        no_lines = len(result)
        self.sendLine(str(no_lines)) 
        for r in result:
            self.sendLine(str(r))

In the above code transport.write(...) does not send across any data to the client. How can I fix this.


Solution

  • The transport.write call will send the data to the client. If the client is poorly written, it may lose it because the connection closes immediately after the data is sent. There are many other possible ways the client could fail, too, but there's no way to know what's actually happening since the client code isn't part of the question.