Explore the newly introduced Asyncio module in Python3.4 _python

Source: Internet
Author: User
Tags call back

Using Simple Protocol

Asyncio. The Baseprotocol class is a common base class for protocol interfaces (Protocol interface) in Asyncio modules. Asyncio. Protocolclass inherits from Asyncio. Baseprotocol and provides an interface for the stream protocols. The following code shows the Asyncio. A simple implementation of the Protocol interface, which behaves 1 like an echo server, and also outputs some information in the Python console. Simpleechoprotocol inherits from Asyncio. Protocol, and has implemented 3 methods: Connection_made, data_received and Andconnection_lost:

Import Asyncio class Simpleechoprotocol (Asyncio.
    Protocol): Def connection_made (self, Transport): "" "Called when a connection is made.
    The argument is the transport representing the pipe connection.
    To receive data, wait for data_received () calls.
    When the connection are closed, Connection_lost () is called.
    "" "Print (" Connection received! ")
    Self.transport = Transport def data_received (self, data): "" "Called when some the data is received.
    The argument is a bytes object.
    "" "Print (data) self.transport.write (b ' echo: ') self.transport.write (data) def connection_lost (self, exc):
    "" "called the connection is lost or closed. The argument is a exception object or None (the latter meaning a regular EOF are received or the connection was AB
    orted or closed). "" "Print (" Connection lost! Closing server ... ") server.close () loop = Asyncio.get_event_loop () Server = Loop.run_until_complete (loop.cReate_server (Simpleechoprotocol, ' localhost ', 2222)) Loop.run_until_complete (server.wait_closed ())

 

You can test this echo server by running a telnet client and connecting to the localhost 2222 port. If you are using this port, you can modify the port number to any other ports that you can use. If you use the default value, you can run the above code in the Python console and then run telnet localhost 2222 at the command prompt or terminal. You're going to see Connection received!. Information is displayed in the Python console. Next, any characters you enter in the console of Telnet are displayed in the form of Echo: The characters you enter, and the characters that you just entered are displayed in the Python console. When you exit the Telnet console, you will see connection lost! Closing server ... Information is displayed in the Python console.

For example, if you enter ABC after you open Telnet, you will see the following message in the Telnet window:

 Echo:abecho:bcecho:c

In addition, the following message is displayed in the Python console:

 Connection received!
 B ' A ' B ' b ' B '
 C '
 Connection lost! Closing server ...

After creating an event loop named Loop, the code will call Loop.run_until_complete to run the Loop.create_server (coroutine). This thread creates a TCP server and uses the Protocol factory class to bind to the specified port of the specified host (in this case, the 2222 port on the localhost, the factory class used is Simpleechoprotocol) and returns a server object. To stop the service. The code assigns this instance to the server variable. In this way, when a client connection is established, a new instance of Simpleechoprotocol is created and the methods in the class are executed.

When a connection is successfully created, the code inside the Connection_made method prints a message and assigns the received content as a parameter to the transport member variable for later use in another method.

When the incoming data is received, the code in the data_received aspect outputs the data bytes received, and sends Echo: and receives the data to the client by calling the two-time Self.transport.write method. Of course, you can only call once self.transport.write to return all of the data, but I want to distinguish more clearly between the code that sends echo: and the code that sends the received data.

When the connection is turned off or disconnected, the code in the Connection_lost method outputs a message and calls Server.close (), and the loop that runs until the server shuts down stops running.
using Clients and Servers

In the example above, Telnet is a client. The Asyncio module provides a way for you to easily use stream reader and writer to write server and client. The following code demonstrates a simple echo server that listens for port 2222 on the localhost. You can run the following code in the Python console and then run the client's code as the client in another Python console.

Import Asyncio
 
@asyncio. Coroutine
def simple_echo_server ():
  # Start A socket server, call back to each Clien T connected.
  # The Client_connected_handler coroutine would be automatically converted to a Task
  yield from Asyncio.start_server (CLI Ent_connected_handler, ' localhost ', 2222)
 
@asyncio. Coroutine
def client_connected_handler (Client_reader, Client_writer):
  # runs for each client connected
  # Client_reader be a StreamReader object
  # Client_writer is A StreamWriter object
  print ("Connection received!")
  While True:
    data = yield from Client_reader.read (8192)
    if not data:
      break
    print (data)
    client _writer.write (data)
 
loop = Asyncio.get_event_loop ()
Loop.run_until_complete (Simple_echo_server ())
Try:
  loop.run_forever ()
finally:
  loop.close ()

The following code demonstrates that a client program connects 2222 ports on the localhost and uses Asyncio. The StreamWriter object writes several lines of data and then uses Asyncio. The StreamWriter object reads the data returned by the service side.

Import Asyncio
 
lastline = B ' Last line.\n '
 
@asyncio. Coroutine
 def simple_echo_client ():
  # Open A Connection and write a few lines by using the StreamWriter object
  Reader, writer = yield from asyncio.open_connection ( ' localhost ', 2222)
  # Reader is a StreamReader object
  # Writer is a StreamWriter object
  writer.write (b ' ne.\n ')
  writer.write (b ' Second line.\n ')
  Writer.write (b ' third line.\n ')
  writer.write (lastline)
 
  # Now, read a few lines by using the StreamReader object
  print (' lines received ') while
  True: line
    = y Ield from Reader.readline ()
    print (line)
    if line = = LastLine or not:
      break
  Writer.close ()
 
loop = Asyncio.get_event_loop ()
Loop.run_until_complete (Simple_echo_client ())

You can execute the client's code in a different Python console. If the service is running correctly, the console will output the following:

Lines received
B ' line.\n ' B ' Second line.\n ' B '
third line.\n '
b ' last line.\n '

The Python console that executes the server-side code displays the following:

 Connection received!
 B ' Line.\nsecond line.\nthird line.\nlast line.\n '

First, let's focus on the service-side code. After creating an event loop called Loop, the code invokes Loop.run_until_complete to run the simple_echo_server. The coprocessor calls the Asyncio.start_server to open a socket server, bind to the specified host and port number, and then execute the callback function passed as a parameter for each client connection--client_connected_handler. In this example, Client_connected_handler is another coprocessor and is not automatically converted to a task. In addition to the coroutine, you can specify a normal callback function.

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.