Python network programming - based on the twsited(1)

protocol processing class will usually subclass the twisted.com .internet.protocol. protocol. Most protocol handlers inherit from this class or inherit from one of its convenience subclasses. Instances of the protocol class are instantiated by connection, instantiated on demand, and disappear when the connection is complete. This means that the persistent configuration will not be saved in the protocol.

The persistent configuration is stored in the factory class, which is usually inherited from twisted.com .internet.protocol.Factory. The factory's buildProtocol method is used to create a protocol for each new connection.

It is often useful to be able to provide the same service on multiple ports or network addresses. That's why the factory doesn't listen for connections, and actually doesn't know anything about the network. The

Twisted protocol processes data asynchronously. When an event arrives from the network, the protocol protocol responds to them, and the arrival of the event will invoke the method on the protocol.

This is one of the simplest protocols. It simply writes back what was written, not all events.

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from twisted.internet.protocol import Protocol 
class Echo(Protocol):
    def dataReceived(self, data): 
        self.transport.write(data)

Below is an example of a protocol responding to another event:

from twisted.internet.protocol import Protocol
Class QOTD(Protocol):
    Def connectionMade(self):
        Self.transport.write("An apple a day, don't ask a doctor\r\n")
        self.transport.loseConnection()