欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

探索Python3.4中新引入的asyncio模塊

 更新時(shí)間:2015年04月08日 10:48:45   投稿:goldensun  
這篇文章主要介紹了Python3.4中新引入的asyncio模塊,包括其對(duì)端口和服務(wù)器等的操作,需要的朋友可以參考下

使用 Simple Protocol

asyncio.BaseProtocol 類(lèi)是asyncio模塊中協(xié)議接口(protocol interface)的一個(gè)常見(jiàn)的基類(lèi)。asyncio.Protocolclass 繼承自asyncio.BaseProtocol 并為stream protocols提供了一個(gè)接口。下面的代碼演示了asyncio.Protocol 接口的一個(gè)簡(jiǎn)單實(shí)現(xiàn),它的行為1就像一個(gè)echo server,同時(shí),它還會(huì)在Python的控制臺(tái)中輸出一些信息。SimpleEchoProtocol 繼承自asyncio.Protocol,并且實(shí)現(xiàn)了3個(gè)方法:connection_made, data_received 以及 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 is 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 is received or the connection was
    aborted 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())

你可以通過(guò)運(yùn)行一個(gè)telnet客戶(hù)端程序,并且連接到localhost的2222端口來(lái)測(cè)試這個(gè)echo server。如果你正在使用這個(gè)端口,你可以將這個(gè)端口號(hào)修改為任何其他可以使用的端口。如果你使用默認(rèn)的值,你可以在Python的控制臺(tái)中運(yùn)行上面的代碼,之后在命令提示符或終端中運(yùn)行 telnet localhost 2222。你將會(huì)看到 Connection received! 的信息顯示在Python的控制臺(tái)中。接下來(lái),你在telnet的控制臺(tái)中輸入的任何字符都會(huì)以echo:跟上輸入的字符的形式展示出來(lái),同時(shí),在Python的控制臺(tái)中會(huì)顯示出剛才新輸入的字符。當(dāng)你退出telnet控制臺(tái)時(shí),你會(huì)看到Connection lost! Closing server... 的信息展示在Python的控制臺(tái)中。

舉個(gè)例子,如果你在開(kāi)啟telnet之后輸入 abc,你將會(huì)在telnet的窗口中看到下面的消息:

 echo:abecho:bcecho:c

此外,在Python的控制臺(tái)中會(huì)顯示下面的消息:

 Connection received!
 b'a'
 b'b'
 b'c'
 Connection lost! Closing server...

在創(chuàng)建了一個(gè)名為loop的事件循環(huán)之后,代碼將會(huì)調(diào)用loop.run_until_complete來(lái)運(yùn)行l(wèi)oop.create_server這個(gè)協(xié)程(coroutine)。這個(gè)協(xié)程創(chuàng)建了一個(gè)TCP服務(wù)器并使用protocol的工廠(chǎng)類(lèi)綁定到指定主機(jī)的指定端口(在這個(gè)例子中是localhost上的2222端口,使用的工廠(chǎng)類(lèi)是SimpleEchoProtocol)并返回一個(gè)Server的對(duì)象,以便用來(lái)停止服務(wù)。代碼將這個(gè)實(shí)例賦值給server變量。用這種方式,當(dāng)建立一個(gè)客戶(hù)端連接時(shí),會(huì)創(chuàng)建一個(gè)新的SimpleEchoProtocol的實(shí)例并且該類(lèi)中的方法會(huì)被執(zhí)行。

當(dāng)成功的創(chuàng)建了一個(gè)連接之后,connection_made 方法里面的代碼輸出了一條消息,并將收到的內(nèi)容作為一個(gè)參數(shù)賦值給transport成員變量,以便稍后在另一個(gè)方法中使用。

當(dāng)收到了傳來(lái)的數(shù)據(jù)時(shí),data_received方面里面的代碼會(huì)將收到的數(shù)據(jù)字節(jié)輸出,并且通過(guò)調(diào)用兩次self.transport.write 方法將echo: 和收到數(shù)據(jù)發(fā)送給客戶(hù)端。當(dāng)然了,也可以只調(diào)用一次self.transport.write將所有的數(shù)據(jù)返回,但是我想更清楚的將發(fā)送echo:的代碼和發(fā)送收到的數(shù)據(jù)的代碼區(qū)分開(kāi)來(lái)。

當(dāng)連接關(guān)掉或者斷開(kāi)時(shí),connection_lost方法中的代碼將會(huì)輸出一條消息,并且調(diào)用server.close();此時(shí),那個(gè)在服務(wù)器關(guān)閉前一直運(yùn)行的循環(huán)停止了運(yùn)行。
使用 Clients and Servers

在上面的例子中,telnet是一個(gè)客戶(hù)端。asyncio模塊提供了一個(gè)協(xié)程方便你很容易的使用stream reader 和 writer來(lái)編寫(xiě)服務(wù)端和客戶(hù)端。下面的代碼演示了一個(gè)簡(jiǎn)單的echo server,該server監(jiān)聽(tīng)localhost上的2222端口。你可以在Python的控制臺(tái)中運(yùn)行下面的代碼,之后在另一個(gè)Python的控制臺(tái)中運(yùn)行客戶(hù)端的代碼作為客戶(hù)端。

import asyncio
 
@asyncio.coroutine
def simple_echo_server():
  # Start a socket server, call back for each client connected.
  # The client_connected_handler coroutine will be automatically converted to a Task
  yield from asyncio.start_server(client_connected_handler, 'localhost', 2222)
 
@asyncio.coroutine
def client_connected_handler(client_reader, client_writer):
  # Runs for each client connected
  # client_reader is 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()

下面的代碼演示了一個(gè)客戶(hù)端程序連接了localhost上的2222端口,并且使用asyncio.StreamWriter對(duì)象寫(xiě)了幾行數(shù)據(jù),之后使用asyncio.StreamWriter對(duì)象讀取服務(wù)端返回的數(shù)據(jù)。
 

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.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 = 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())

你可以在不同的Python控制臺(tái)中執(zhí)行客戶(hù)端的代碼。如果服務(wù)端正在運(yùn)行,控制臺(tái)中會(huì)輸出下面的內(nèi)容:

Lines received
b'First line.\n'
b'Second line.\n'
b'Third line.\n'
b'Last line.\n'

執(zhí)行服務(wù)端代碼的Python控制臺(tái)會(huì)顯示下面的內(nèi)容:

 Connection received!
 b'First line.\nSecond line.\nThird line.\nLast line.\n'

首先,讓我們關(guān)注一下服務(wù)端的代碼。在創(chuàng)建完一個(gè)叫l(wèi)oop的事件循環(huán)之后,代碼會(huì)調(diào)用loop.run_until_complete來(lái)運(yùn)行這個(gè)simple_echo_server協(xié)程。該協(xié)程調(diào)用asyncio.start_server協(xié)程來(lái)開(kāi)啟一個(gè)socket服務(wù)器,綁定到指定的主機(jī)和端口號(hào),之后,對(duì)每一個(gè)客戶(hù)端連接執(zhí)行作為參數(shù)傳入的回調(diào)函數(shù)——client_connected_handler。在這個(gè)例子中,client_connected_handler是另一個(gè)協(xié)程,并且不會(huì)被自動(dòng)的轉(zhuǎn)換為一個(gè)Task。除了協(xié)程(coroutine)之外,你可以指定一個(gè)普通的回調(diào)函數(shù)。

相關(guān)文章

  • python?pandas?數(shù)據(jù)排序的幾種常用方法

    python?pandas?數(shù)據(jù)排序的幾種常用方法

    這篇文章主要介紹了python?pandas數(shù)據(jù)排序的幾種常用方法,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • 基于Python實(shí)現(xiàn)主機(jī)遠(yuǎn)程控制

    基于Python實(shí)現(xiàn)主機(jī)遠(yuǎn)程控制

    這篇文章主要介紹了基于Python實(shí)現(xiàn)主機(jī)遠(yuǎn)程控制,本文為?HITwh?網(wǎng)絡(luò)空間安全專(zhuān)業(yè)網(wǎng)絡(luò)空間安全設(shè)計(jì)與實(shí)踐選題,主要實(shí)現(xiàn)了遠(yuǎn)程監(jiān)控局域網(wǎng)內(nèi)的主機(jī)桌面與網(wǎng)絡(luò)情況、簡(jiǎn)單鍵鼠控制、遠(yuǎn)程斷網(wǎng)(ARP?攻擊)、數(shù)據(jù)加密傳輸?shù)裙δ?,下面?lái)看看具體實(shí)現(xiàn)過(guò)程吧
    2022-01-01
  • Python中if有多個(gè)條件處理方法

    Python中if有多個(gè)條件處理方法

    在本篇文章里小編給大家整理的是一篇關(guān)于Python中if有多個(gè)條件處理方法,需要的朋友們可以學(xué)習(xí)參考下。
    2020-02-02
  • Django實(shí)現(xiàn)快速分頁(yè)的方法實(shí)例

    Django實(shí)現(xiàn)快速分頁(yè)的方法實(shí)例

    分頁(yè)是我們?nèi)粘i_(kāi)發(fā)中必不可少的一個(gè)功能,下面這篇文章主要給大家介紹了關(guān)于Django如何實(shí)現(xiàn)快速分頁(yè)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-10-10
  • python魔法方法之__setattr__()

    python魔法方法之__setattr__()

    這篇文章主要介紹了python魔法方法之__setattr__(),python提供了諸多的魔法方法,其中__setattr__()方法主要用于類(lèi)實(shí)例進(jìn)行屬性賦值,接下來(lái)請(qǐng)和小編一起進(jìn)入文章來(lái)了解更多相關(guān)內(nèi)容吧
    2022-03-03
  • python代碼中怎么換行

    python代碼中怎么換行

    這篇文章主要介紹了python代碼中怎么換行的相關(guān)知識(shí)點(diǎn)以及方法,需要的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • 聊聊boost?python3依賴(lài)安裝問(wèn)題

    聊聊boost?python3依賴(lài)安裝問(wèn)題

    這篇文章主要介紹了boost?python3依賴(lài)安裝,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • python腳本監(jiān)控Tomcat服務(wù)器的方法

    python腳本監(jiān)控Tomcat服務(wù)器的方法

    這篇文章主要介紹了利用python腳本監(jiān)控Tomcat服務(wù)器的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-07-07
  • Python中subprocess介紹及如何使用詳細(xì)講解

    Python中subprocess介紹及如何使用詳細(xì)講解

    在實(shí)際開(kāi)發(fā)過(guò)程中,我們經(jīng)常會(huì)遇到需要從Python腳本中調(diào)用外部程序或腳本的場(chǎng)景,下面這篇文章主要給大家介紹了關(guān)于Python中subprocess介紹及如何使用詳細(xì)講解的相關(guān)資料,需要的朋友可以參考下
    2024-09-09
  • PyQt5每天必學(xué)之組合框

    PyQt5每天必學(xué)之組合框

    這篇文章主要為大家詳細(xì)介紹了PyQt5每天必學(xué)之組合框,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04

最新評(píng)論