Write a simple network client using the Python twisted framework _python

Source: Internet
Author: User
Tags documentation joins

Protocol
as with the server, it is implemented through this class. Let's look at a short routine:

From Twisted.internet.protocol import protocol from
SYS import stdout

class Echo (protocol):
  def DataReceived (self, data):
    stdout.write (data)

In this program, it is simply the output of the obtained data to the standard output to display, there are many other events did not make any response, the following
There is an example that responds to other events:

From Twisted.internet.protocol Import Protocol

class Welcomemessage (protocol):
  def connectionmade (self):
    self.transport.write ("Hello server, I am the client!/r/n")
    self.transport.loseConnection ()

This protocol connects to the server, sends a greeting message, and then closes the connection.
Connectionmade events are usually triggered when an event that establishes a connection occurs. The Connectionlost event function is triggered when the connection is closed

(Simple, Single-use clients) Easy Single User Client
In many cases, protocol only needs to connect to the server once, and the code is simply to obtain an instance of a protocol connection. In
In this case, Twisted.internet.protocol.ClientCreator provides an appropriate API

From twisted.internet import reactor
from Twisted.internet.protocol Import protocol, Clientcreator

class Greeter (Protocol):
  def sendmessage (self, msg):
    self.transport.write ("message%s/n"% msg)

def Gotprotocol (P):
  p.sendmessage ("Hello")
  reactor.calllater (1, P.sendmessage, "this are sent in a second")
  Reactor.calllater (2, p.transport.loseconnection)

C = Clientcreator (reactor, Greeter)
c.connecttcp (" localhost ", 1234). Addcallback (Gotprotocol)


clientfactory (Customer Factory)
Clientfactory is responsible for creating protocol and returning the connection status of related events. This allows it to do something like a connection error and then
Reconnect the thing. Here's a simple example of clientfactory using the Echo protocol and printing the current connection state

From Twisted.internet.protocol import protocol, clientfactory from
sys import stdout

class Echo (protocol):
  def datareceived (self, data):
    stdout.write (data)

class Echoclientfactory (clientfactory):
  def Startedconnecting (self, connector):
    print ' started to connect. '
  
  def buildprotocol (self, addr):
    print ' Connected. '
    Return Echo ()
  
  def clientconnectionlost (self, connector, reason):
    print ' Lost connection. Reason: ', Reason
  
  def clientconnectionfailed (self, connector, Reason):
    print ' Connection failed. Reason: ', Reason

To connect Echoclientfactory to the server, you can use the following code:

From twisted.internet Import reactor
reactor.connecttcp (host, Port, Echoclientfactory ())
Reactor.run ()

Note: The clientconnectionfailed is invoked when the connection cannot be built, Clientconnectionlost is invoked when the connection is closed, and the two are different.


Reconnection (Reconnect)
many times, client connections may often be disconnected due to network errors. One way to re-establish a connection is to call it when the connection is disconnected

Connector.connect () method.

From Twisted.internet.protocol import Clientfactory

class Echoclientfactory (clientfactory):
  def Clientconnectionlost (self, connector, reason):
    connector.connect ()

Connector is an interface between connection and protocol that is passed as the first argument to Clientconnectionlost,

Factory can call the Connector.connect () method to reconnect
However, many programs use the Reconnectingclientfactory function in place of the connection failure and connection disconnect to reconnect.

function and try to reconnect again and again. Here's an example of ECHO protocol using reconnectingclientfactory:

From Twisted.internet.protocol Import protocol, reconnectingclientfactory the from
sys import stdout

class Echo ( Protocol):
  def datareceived (self, data):
    stdout.write (data)

class Echoclientfactory ( Reconnectingclientfactory):
  def startedconnecting (self, connector):
    print ' started to connect. '

  def buildprotocol (self, addr):
    print ' Connected. '
    print ' resetting reconnection delay '
    self.resetdelay () return
    Echo ()

  def clientconnectionlost (self, Connector, reason):
    print ' Lost connection. Reason: ', Reason
    reconnectingclientfactory.clientconnectionlost (self, connector, Reason)

  def Clientconnectionfailed (self, connector, reason):
    print ' Connection failed. Reason: ', Reason
    reconnectingclientfactory.clientconnectionfailed (self, Connector,reason)


A Higher-level Example:irclogbot
All of the above examples are very simple, and here is a more complex example from the Doc/examples directory

# Twisted imports from Twisted.words.protocols import IRC from twisted.internet Import reactor, protocol from TWISTED.PYT Hon Import Log # System imports import time, SYS class Messagelogger: ' "' an independent logger class (because Sepa
  Ration of application and protocol logic is a good thing).
    "" "Def __init__ (self, file): self.file = File def log (self, message):" "" "" "" "" "" "" timestamp = Time.strftime ("[%h:%m:%s]", Time.localtime (Time.time ()) Self.file.write ('%s%s/n '% (timestamp, message ) Self.file.flush () def close (self): Self.file.close () class Logbot (IRC).

  ircclient): "" "A Logging IRC bot." " Nickname = "Twistedbot" def Connectionmade (self): IRC. Ircclient.connectionmade (self) Self.logger = Messagelogger (open (Self.factory.filename, "a") self.logger.log ("[Con Nected at%s] "% Time.asctime (Time.localtime (Time.time ())) def connectionlost (self, Reason): IRC. Ircclient.connectionloSt (Self, Reason) Self.logger.log ("[Disconnected at%s]"% Time.asctime (Time.localtime (Time.time ())) s Elf.logger.close () # Callbacks for the events Def Signedon (self): "" "Called when bot has succesfully signed in to S
    erver. "" " Self.join (Self.factory.channel) def joined (self, Channel): "" "This'll get called when the bot joins the channel." "" Self.logger.log ("[I have joined%s]"% channel) def privmsg (self, user, channel, msg): "" "This'll get called
    Ed when the bot receives a message. "" user = User.split ('! ', 1) [0] Self.logger.log ("<%s>%s"% (user, msg)) # Check to ' if they ' re sending me A private message if channel = = Self.nickname:msg = "It isn ' t nice to whisper!
      Play nice with the group. Self.msg (user, MSG) return # Otherwise check to the if it is a message directed at me if Msg.startswith (sel
F.nickname + ":"): Msg = "%s:i am a log bot"% User self.msg (channel, MSG)      Self.logger.log ("<%s>%s"% (Self.nickname, msg)) def action (self, user, channel, msg): "" This would ge
    T called when the bot sees someone does an action. ""  user = User.split ('! ', 1) [0] Self.logger.log ("*%s%s"% (user, msg)) # IRC callbacks def irc_nick (self, prefix,
    params): "" "called an IRC user changes their nickname." " Old_nick = Prefix.split ('! ') [0] New_nick = params[0] Self.logger.log ("%s is now known as%s"% (Old_nick, New_nick)) class Logbotfactory (pro Tocol.

  clientfactory): "" A factory for Logbots.
  A new Protocol instance would be created each time we connect to the server.  "" "# The class of the ' protocol to build ' when new connection is made protocol = Logbot def __init__ (self, channel,
    FileName): Self.channel = Channel Self.filename = filename def clientconnectionlost (self, connector, reason):
    "" "If we get disconnected, reconnect to server." " Connector.connect () def clientconnectionfAiled (self, connector, reason): print "Connection failed:", reason Reactor.stop () if __name__ = ' __main__ ': # Initialize logging log.startlogging (sys.stdout) # Create factory protocol and application F = logbotfactory (sys.ar GV[1], sys.argv[2]) # Connect factory to this host and Port reactor.connecttcp ("irc.freenode.net", 6667, F) # Run

 Bot Reactor.run ()

Irclogbot.py connects to the IRC server, joins a channel, and records all communication information in the file, indicating that the logical and persistent data at the connection level for reconnection at disconnect is stored in factory.

Persistent Data in the Factory
Because protocol is rebuilt each time the connection is made, the client needs to record the data in some way to ensure persistence. It's like a log robot. He needs to know that the channel is landing and landing somewhere.

From twisted.internet import protocol from
twisted.protocols import IRC

class Logbot (IRC. Ircclient):

  def connectionmade (self):
    IRC. Ircclient.connectionmade (self)
    Self.logger = Messagelogger (open (Self.factory.filename, "a"
    ) Self.logger.log ("[connected at%s]"%
            time.asctime (Time.localtime (Time.time ()))
  
  def Signedon (self):
    Self.join (Self.factory.channel)

  
class logbotfactory (protocol. Clientfactory):
  
  protocol = Logbot
  
  def __init__ (self, Channel, filename):
    Self.channel = Channel
    Self.filename = filename

When protocol is created, Factory gets a reference to an instance of himself. Then, you can have his attributes in the factory.

More information:
  The protocol class described in this document is a subclass of Iprotocol, Iprotocol conveniently applied to a large number of twisted applications. To learn the complete Iprotocol interface, refer to the API documentation Iprotocol.
  The Trasport properties used in some examples of this document provide a Itcptransport interface to learn the full interface, refer to the API documentation Itcptransport
  Interface classes are a way to specify what methods and attributes are available for an object and how they behave. Reference components:interfaces and Adapters document

Related Article

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.