Question

I start to learn Twisted and try to complete my first task. I have next server code:

class TextProtocol(Protocol):

    def connectionMade(self):
        text = self.factory.text
        self.transport.write(text)
        self.transport.loseConnection()

class TextServerFactory(ServerFactory):

    protocol = TextProtocol

    def __init__(self, text):
        self.text = text

from twisted.internet import reactor
reactor.listenTCP(4444, TextServerFactory("Twisted"))
reactor.run()

This code send text to client immediatelly. But actually I want to send data, by letters: if we will have a lot of clients, server should send letter by letter successively. I think SERVER log should be something like this:

Client #1 connected

Sending "T" to client #1
Sending "w" to client #1

Client #2 connected

Sending "T" to client #2
Sending "i" to client #1
Sending "w" to client #2
Sending "s" to client #1
Sending "i" to client #2

.....

If i will create loop in protocol it will be blocking operation. Could you help me with this?

Était-ce utile?

La solution

TCP is going to group/batch/split things as it see fit (its trying to optimize the connection), see this answer by Glyph or this more detailed How can I force a socket to send the data in its buffer article

If you really want to do this, and mind you your trying to force TCP to do something it doesn't want, then Jean-Paul's answer is pointing that the fact that you might be able to get a char-by-char flush on TCP if you write one char at a time with a few second wait in-between each char.

Autres conseils

Take a look at twisted.internet.task.LoopingCall and twisted.internet.IReactorTime.callLater.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top