More detailed examples of protocol and factory

Source: Internet
Author: User
from twisted.internet.protocol import Protocol, Factoryfrom twisted.internet import reactorclass QuoteProtocol(Protocol):     def __init__(self, factory):          self.factory = factory     def connectionMade(self):          self.factory.numConnections += 1     def dataReceived(self, data):          print 'num of connections : ', self.factory.numConnections          print 'received : ' + data          print 'sendding : ' + self.getQuote()          self.transport.write(self.getQuote())          self.updateQuote(data)     def getQuote(self):          return self.factory.quote     def updateQuote(self, quote):          self.factory.quote = quote     def connectionLost(self, reason):          self.factory.numConnections -= 1class QuoteFactory(Factory):     numConnections = 0          def __init__(self, quote = None):          self.quote = quote or 'An apple a day keeps a doctor away'     def buildProtocol(self, addr):          return QuoteProtocol(self)reactor.listenTCP(8000, QuoteFactory())reactor.run()

On the server side, the quotefactory object is assigned a quote attribute during instantiation. This class also has a global attribute numconnections used to record the current number of connections. When a quoteprotocol object is instantiated, it is assigned a quotefactory attribute, that is, the quotefactory object that was previously instantiated.

When a connection is established, the numconnections attribute in the quotefactory attribute of the quoteprotocol object is added to 1. When the connection is disconnected, this attribute is reduced by one. When receiving client data, the current number of connections is displayed first, and then the quote attribute is sent to the client. Then, the quote is changed to Data.

from twisted.internet import reactorfrom twisted.internet.protocol import Protocol, ClientFactoryclass QuoteProtocol(Protocol):     def __init__(self, factory):          self.factory = factory     def sendQuote(self):          self.transport.write(self.factory.quote)     def connectionMade(self):          self.sendQuote()     def dataReceived(self, data):          print 'Received data : ' + data          self.transport.loseConnection()class QuoteClientFactory(ClientFactory):     def __init__(self, quote):          self.quote = quote     def buildProtocol(self, addr):          return QuoteProtocol(self)     def clientConnectionFailed(self, connector, reason):          print 'connection failed: ' + reason.getErrorMessage()          maybeStopReactor()     def clientConnectionLost(self, connector, reason):          print 'connection lost : ' + reason.getErrorMessage()          maybeStopReactor()def maybeStopReactor():     global quote_counter     quote_counter -= 1     if not quote_counter:          reactor.stop()quotes = ['you snooze you lose',         'the early bird gets the worm',         'carpe diem'     ]quote_counter = len(quotes)for quote in quotes:     reactor.connectTCP('localhost', 8000, QuoteClientFactory(quote))reactor.run()

The client initiates three connections (three different quoteclientfactory instances) to the server. Each connection transmits the quote list (quoteclientfactory's quote attribute) when the connection is established, when the server responds, the connection is disconnected.

In this example, Protocol corresponds to the connection. It is created when the connection is established and destroyed when the connection is disconnected.

If you want to save some information, you need to put it in the factory

The server displays the following information:

Num of connections: 1
Written ED: You Snooze you lose
Sendding: An apple a day keeps a doctor away
Num of connections: 3
Received: The early bird gets the worm
Sendding: You Snooze you lose
Num of connections: 3
Received: carpe diem
Sendding: The early bird gets the worm

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.