Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Twisted Finger Example

DZone's Guide to

Twisted Finger Example

·
Free Resource

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)
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}