ltprotocol is a Python module that provides a Twisted-based client and server implementation for protocols which begin with a legnth and type field. Create your protocol by constructing an LTProtocol with a list of LTMessage objects which specify your protocol. Use LTTwistedServer and LTTwistedClient to create a server or client.
Example: A complete example can be downloaded here. To try it out, run:
python test_lpprotocol.py server
python test_lpprotocol.py client
To use it, you first define the messages in your protocol:
class NumMsg(LTMessage):
@staticmethod
def get_type():
return 1
def __init__(self, n):
LTMessage.__init__(self)
self.num = n
def pack(self):
return struct.pack("> I", self.num)
@staticmethod
def unpack(body):
return NumMsg(struct.unpack("> I", body)[0])
def __str__(self):
return str(self.num)
class StrMsg(LTMessage):
@staticmethod
def get_type():
return 2
def __init__(self, s):
LTMessage.__init__(self)
self.str = s
def pack(self):
return struct.pack("> %us" % len(self.str), self.str)
@staticmethod
def unpack(body):
return StrMsg(struct.unpack("> %us" % len(body), body)[0])
def __str__(self):
return self.str
When your client or server receives data, it posts a callback to a method you specify. For this example, I am going to use this helper function to simply print out the messages we receive:
def print_ltm(prefix, ltm):
print '%s got: %s' % (prefix, str(ltm))
To create a client, I would do something like this (the second argument is the function to call when a complete message has arrived):
p = LTProtocol([NumMsg, StrMsg])
client = LTTwistedClient(p, lambda m : print_ltm('client', m))
client.connect('127.0.0.1', 9999)
Likewise, to create a server I would do something like this:
p = LTProtocol([NumMsg, StrMsg])
server = LTTwistedServer(p, lambda m : print_ltm('server', m))
server.listen(9999)
You may want to override the buildProtocol() method of the LTTwistedClient class to have the client send some message to the server when it first connects rather than waiting for the server to send it something. Alternatively, you might subclass the LTTwistedProtocol class (setting LTTwistedServer.protocol to your new subclass) in order to have the server send some message to the client when it connects, or to take some special action when the client disconnects.
Product's homepage
Requirements:
· Python