Explore the newly introduced Asyncio module in Python3.4

Source: Internet
Author: User
Tags call back
using simple Protocol

Asyncio. The Baseprotocol class is a common base class for the Protocol interface (Protocol interface) in the Asyncio module. Asyncio. Protocolclass inherits from Asyncio. Baseprotocol and provides an interface for stream protocols. The following code demonstrates 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 implemented 3 methods: Connection_made, Data_received, and Andconnection_lost:

Import Asyncio class Simpleechoprotocol (Asyncio.    Protocol): Def connection_made (self, Transport): "" "called If 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 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 when the connection is lost or closed. The argument is an exception object or None (the latter meaning a regular EOF are received or the connection was Abor    Ted 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 program and connecting to port 2222 on localhost. If you are using this port, you can change this to any other port 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 in 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 Telnet console are displayed as Echo: followed by the characters you entered, and the characters you just entered are shown 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 turn on Telnet, you will see the following message in the Telnet window:

Echo:abecho:bcecho:c

Additionally, 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 called Loop, the code calls Loop.run_until_complete to run the Loop.create_server (coroutine). This process creates a TCP server and uses the Protocol factory class to bind to the specified port on the specified host (in this case, port 2222 on localhost, the factory class is Simpleechoprotocol) and returns a server object. To use 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 that class are executed.

After the successful creation of a connection, the code inside the Connection_made method outputs a message and assigns the received content as a parameter to the transport member variable for later use in another method.

When the transmitted data is received, the code inside the data_received will output the data bytes received, and send echo: And receive the data to the client by calling the two-Self.transport.write method. Of course, you can just call Self.transport.write to return all the data, but I want to make it clearer to distinguish 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 process that makes it easy for you to use stream reader and writer to write server and client. The following code shows a simple echo server that listens on port 2222 on localhost. You can run the following code in the Python console and then run the client's code as a client in another Python console.

Import Asyncio @asyncio. Coroutinedef simple_echo_server ():  # Start A socket server, call back to each client connecte D.  # The Client_connected_handler coroutine'll be is automatically converted to a Task  yield from Asyncio.start_server (CLI Ent_connected_handler, ' localhost ', 2222) @asyncio. Coroutinedef Client_connected_handler (Client_reader, Client_ Writer):  # Runs for each client connected  # Client_reader are a StreamReader object  # Client_writer is a Stream Writer Object  Print ("Connection received!")  While True: the    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 shows that a client program connects to port 2222 on localhost and uses Asyncio. The StreamWriter object writes a few 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 ' first line.\n ')  WRITER.WR Ite (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    = yield from reader.readline ()    print (line)    if line = = LastLine or not line: 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 receivedb ' first line.\n ' B ' Second line.\n ' B ' third line.\n ' B ' last line.\n '

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

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

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

  • 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.