DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Twisted Finger Example

06.16.2007
| 2000 views |
  • submit to reddit
        
from twisted.application import internet, service
from twisted.internet import reactor, protocol, defer
from twisted.protocols import basic

class FingerProtocol(basic.LineReceiver):

    def lineReceived(self, user):
        defer = self.factory.get_user(user)
        defer.addErrback(lambda _: 'Internal server error')
        defer.addCallback(self.send_info)

    def send_info(self, info):
        self.transport.write(info + '\r\n')
        self.transport.loseConnection()

class FingerFactory(protocol.ServerFactory):

    protocol = FingerProtocol

    def __init__(self, **users):
        self.users = users

    def get_user(self, user):
        return defer.succeed(self.users.get(user, 'No such user'))

class FingerSetterProtocol(basic.LineReceiver):

    def connectionMade(self):
        self.lines = []

    def lineReceived(self, line):
        self.lines.append(line)

    def connectionLost(self, reason):
        self.factory.set_user(*self.lines[:2])

class FingerSetterFactory(protocol.ServerFactory):

    protocol = FingerSetterProtocol

    def __init__(self, ff):
        self.set_user = ff.users.__setitem__

finger_factory = FingerFactory(sheep='beee')
finger_setter_factory = FingerSetterFactory(finger_factory)

application = service.Application('finger', uid=1, gid=1)
service_collection = service.IServiceCollection(application)
internet.TCPServer(79, finger_factory).setServiceParent(
        service_collection)
internet.TCPServer(1079, finger_setter_factory).setServiceParent(
        service_collection)