Using the Python twisted framework to implement a simple server

Source: Internet
Author: User
Preview
Twisted is a very flexible framework designed so that you can write very powerful servers. This flexible cost is the need to implement your server through several levels, this document describes the protocol layer, you will perform protocol analysis and processing at this level, if you are executing an application, then you should read the top The level for Twisted Write plugin section of how to start writing twisted application after reading this chapter. This document is only related to Tcp,ssl and UNIX socket servers, and there will be another document dedicated to UDP.
Your protocol processing class is typically a subclass of Twisted.internet.protocol.Protocol. Many protocols deal with subclasses of the class that inherit from the class or are more convenient than that class. An instance of a protocol class may be repeatedly connected or destroyed after the connection is closed. This means that the constant configuration information is not saved in protocol.
These persistent configurations are stored in the factory (Factory) class, which typically inherits to Twisted.internet.protocol.Factory, and the default factory class simply instantiates each protocol. Then set their Factory property to this default factory instance itself. This allows each protocol to be stored and then possibly modified, thus creating a protocol persistence.
It is often useful to provide the same service for multiple ports or network addresses. This is why factory does not listen to the connection, and in fact it does not know anything about the network. See Twisted.internet.interfaces.IReactorTCP.listenTCP, another ireactor*.listen* get more information.


This document will explain each step.


Protocol
As mentioned above, this will be understood by more code helper classes and functions. A twisted PROTOCL processes data asynchronously. This means that protocol never waits for any events. Instead, respond when the event arrives over the network.

From Twisted.internet.protocol import Protocolclass Echo (protocol): Def datareceived (self,data):  self.transport.writed (data)

This is a very simple protocol process that simply sends the received data back in the event of data acquisition and does not respond to all events. Here is an example of a protocol response to other events as follows:

From Twisted.internet.protocol import Protocolclass QOTD (protocol): Def Connectionmade (self):  Self.transport.write ("An apple a day keeps the Doctor away/r/n")   self.transport.loseConnection ()

This PROTOCL responds when a known reference has just started to connect, sends a message, and then terminates the connection Connectionmade event is usually triggered when the connection object establishes the initial connection. Just like the QOTD class above is actually a protocol base class for the RFC865 document Connectionlost event will be triggered when disconnected. Instance:

Pythoncode:
 
 
 from Import Protocol  class Echo (Protocol):   def Connectionmade (self):    self.factory.numProtocols = self.factory.numprotocols+1    if self.factory.numProtocols >:     self.transport.write (  Try later ")     Self.transport.loseConnection ()   def connectionlost (self, Reason):    self.factory.numProtocols = Self.factory.numprotocols-1   def datareceived (self, data):    self.transport.write (data)

In this example, Connectionmade and connectionlost work together to keep the number of active connections within the factory up to 100. Whenever there is a user protocol connection, the number of active connections inside the factory is detected, and if the number exceeds 100, the number of connections is sent too much for the next test message, and then disconnected and connectionlost is triggered when a protocol is disconnected, Subtract the number of protocols inside the factory.

Using the Protocol

In this section, I'm going to explain how to simply test your protocol. (Want to know how to write a good twisted server, see Writing plug-ins
For Twisted), here's a code that will run the QOTD server we discussed above:

 
    Pythoncode:
 
 
 from Import Protocol, Factory from  import reactor  class QOTD (Protocol):   def Connectionmade (self):    self.transport.write ("An apple a day keeps the Doctor away/r/n")    Self.transport.loseConnection ()    # Next lines is Magic:  factory = Factory ()  Factory.protocol = QOTD is the port of the     want to run under. Choose something >1024  reactor.listentcp (8007, Factory)  Reactor.run ()

Don't worry about the last 6 code, you'll learn about them later in this document.

Helper protocols

Most protocols rely on lower-level super classes of the same class. The most popular Internet protocol is line-based, and the line is usually made up of CR_LF (carriage return line-wrapping)
However, quite a few of the protocols are mixed, they have linear basic nodes, and they have raw data nodes, such as http/1.1.
In this case, we can use Linereceiver, this protocol class has two different event handling methods, Linereceived and rawdatareceived
By default, only linereceived will be called, one line at a time, but if Setrawmode is called, protocol will call rawdatareceived
To process until Setlinemode is called. Here is a simple example of how to use Linereceiver:

Pythoncode:

From Twisted.protocols.basic import Linereceiverclass Answer (linereceiver): answers = {' How is '? ': ' Fine ', None: ' I D On ' t know-mean "} def linereceived (self, line):  if Self.answers.has_key (line):   Self.sendline ( Self.answers[line])  else:   self.sendline (Self.answers[none])

Note: The delimiter is not part of the command line
Other non-popular protocols still exist, such as netstring based and a prefixed-message-length

State machines

Many twisted protocol handlers need to write a state machine to record their current state, here are some suggestions for writing state machines:
1, do not write large state machine, rather to achieve an abstract state machine class
2. Use the dynamic nature of Python to create an unrestricted state machine, such as an SMTP client
3, do not mix specific application code and protocol processing Code, when the protocol processor has put forward a special specific requirements, keep it as a method call.

Factories (Factory Class)

As previously mentioned, it is usually twisted.internet.protocol.Factory to start work without having to subclass it. However, sometimes protocol need specific
Special plant configuration information or other requirements, in which case, sub-class is required.
For factory, he simply instantiates a special protocol protocol class, instantiates factory, and sets the Protocol property:

Pythoncode:

From Twisted.internet.protocol import factoryfrom twisted.protocols.wire Import echomyfactory = Factory () Myfactory.protocol = Echo

A factory function is useful if you need to simply construct a factory class with specific information:

Pythoncode:

Class QOTD (Protocol): def connectionmade (self):  self.transport.write (self.factory.quote+ '/r/n ')  Self.transport.loseConnection () def makeqotdfactory (quote=none): Factory = Factory () Factory.protocol = QOTD Factory.quote = Quote or ' an apple a day keeps the doctor away ' return factory


A factory has two methods to perform application-specific setup and removal (because a factory is usually present, so general is not in __init__ or
__del__ they are assigned and recycled, it may be too early or too late.
Here is an example of a factory that will allow protocol to write a log file:
Pythoncode:

From Twisted.internet.protocol import factoryfrom twisted.protocols.basic import Linereceiverclass loggingprotocol ( Linereceiver): Def linereceived (self, line):  self.factory.fp.write (line+ '/n ') class Logfilefactory (Factory): protocol = Loggingprotocol def __init__ (self, filename):  self.file = FileName def startfactory (self):  SELF.FP = O Pen (self.file, ' a ') def stopfactory (self):  self.fp.close ()

Putting it all Together (consolidated)

Now that you've learned about factory and want to perform QOTD as a configurable quote server, right? No problem there's a code here:
Pythoncode:

From Twisted.internet.protocol import Factory, protocolfrom twisted.internet import reactorclass QOTD (protocol): def Connectionmade (self):  self.transport.write (self.factory.quote+ '/r/n ')  self.transport.loseConnection () Class Qotdfactory (Factory): protocol = QOTD def __init__ (self, quote=none):  self.quote = quote or ' an apple a day keep s the Doctor away ' Reactor.listentcp (8007, qotdfactory ("configurable quote")) Reactor.run ()

It is the last two lines of code that need to be understood.
Listentcp is a way to connect factory to the network, and he uses the reactor interface, allowing many different loops to handle network code without needing to modify the
End user code, just like this. As stated earlier, if you want to write a good twisted server instead of just 20 lines, then you need to use the Application object.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.