Socket communications

Jp Calderone exarkun at
Thu Jan 16 18:13:03 CET 2003

On Thu, Jan 16, 2003 at 03:13:13PM +0100, Stefano Covino wrote:
> Thank you a lot for you ready answer.
> Basically, what I want to implement is a very simple protocol. I need to 
> send fixed-length messages, and getting and answer again of fixed-length. 
> The communication should be effective on both side.
> I do not know which protocol I should apply. This is the first time I try 
> study this problem and I am still lacking of even the vocabulary.
> In principle a telnet (or ssh) like protocol should work, but I need an as 
> quick as possible connection. The messages are coming from previously 
> defines IP addresses, and I do not need to recognize the user.

  Twisted makes implementing this kind of protocol trivial.

(Untested code)

from twisted.internet import protocol

class FixedLengthProtocol(protocol.Protocol):
    # Length of messages to receive
    length = None
    # Buffer accumulating the current message
    buffer = None

    def __init__(self, length = 512):
        self.length = length
        self.buffer = []
        self.count = 0

    def dataReceived(self, data):
        L = len(data)
        if self.count + L > self.length:
                ''.join(self.buffer + [data[:self.length - self.count]]
            self.buffer = [data[self.length - self.count:]]
            self.count = len(self.buffer[0])
            self.count += L

    def connectionMade(self):
        """Override me"""

    def messageReceived(self, message):
        """Override me"""

    def sendMessage(self, message):
        assert len(message) == self.length

from twisted.internet import reactor

f = protocol.ServerFactory()         # Server
f.protocol = FixedLengthProtocol     # Server

# f = protocol.ClientFactory()       # Client
# f.protocol = FixedLengthProtocol   # Client

reactor.listenTCP(port, f)           # Server
# reactor.connectTCP(host, port, f)  # Client


There are 10 kinds of people: those who understand binary and those who do
 12:00am up 31 days, 9:48, 2 users, load average: 0.07, 0.09, 0.04
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list