python socketserver架構解析,pythonsocketserver

來源:互聯網
上載者:User

python socketserver架構解析,pythonsocketserver

socketserver架構是一個基本的socket伺服器端架構, 使用了threading來處理多個用戶端的串連, 使用seletor模組來處理高並發訪問, 是值得一看的python 標準庫的源碼之一

對於select網路架構的理解可以看 << python select.select模組通訊全過程詳解 >>。socketserver架構採用了selector架構來供你選擇相適應的網路通訊架構, 比如select, poll, epoll等。有了這些網路架構我們就能處理高並發的網路訪問了. 先看看範例程式碼吧:

# coding: utf-8import socketserverclass MyTCPHandler(socketserver.BaseRequestHandler):    """    The request handler class for our server.    It is instantiated once per connection to the server, and must    override the handle() method to implement communication to the    client.    """    def handle(self):        # self.request is the TCP socket connected to the client        self.data = self.request.recv(1024).strip()        print("{} wrote:".format(self.client_address[0]))        print(self.data)        # just send back the same data, but upper-cased        self.request.sendall(self.data.upper())if __name__ == "__main__":    HOST, PORT = "localhost", 9999    # Create the server, binding to localhost on port 9999    # 如果子類沒有某個方法或是屬性, 就回去父類中調用    with socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) as server:        # Activate the server; this will keep running until you        # interrupt the program with Ctrl-C        server.serve_forever()

用戶端:

# coding: utf-8import socketsk = socket.socket()sk.connect(("127.0.0.1", 9999))  # 主動初始化與伺服器端的串連while True:    send_data = input("輸入發送內容:")    sk.sendall(bytes(send_data, encoding="utf8"))    if send_data == "byebye":        break    accept_data = str(sk.recv(1024), encoding="utf8")    print("".join(("接收內容:", accept_data)))sk.close()

我們建立一個繼承自BaseRequestHandler類的TCP請求處理類, 說白了這個類就是我們自己封裝的基於socket的recv()函數與send()函數的類,  而所謂的TCP請求處理類其實就是對socket伺服器端的bind, listen, accept等處理的封裝類, 而且這個封裝的並不是簡單的socket, 而是基於select或是epoll等網路架構的類, 我們調用這個類就能輕易地處理高並發的網路訪問. 其實認真閱讀源碼, 你會發現整體的程式設計是基於事件驅動的, 事件驅動機制的三個要素: 訊息(事件)隊列, 訊息(事件)觸發, 事件迴圈。只不過socketserver架構的事件驅動機制就做到了socket的accept()方法那, 接下來的訊息接受(recv)與發送(send)就沒有在做封裝成相應的事件來進行處理了。

在這裡說一個要注意的地方, 我使用了ThreadingTCPServer()類響應多個用戶端的串連, 但是當我閱讀這個類的源碼的時候, 表示很疑惑啊!

class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass

這讓我很疑惑啊, 再看看調用:

with socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) as server:        # Activate the server; this will keep running until you        # interrupt the program with Ctrl-C        server.serve_forever()

這更疑惑, ThreadingTCPServer哪來的建構函式, 後來研究了一下, 原來當子類的某個函數或是屬性發生調用時, 如果不是重載了父類的方法或是屬性, 而且子類中沒有這個方法或是屬性, 就會去調用父類相對應的方法或是屬性, 於是上面的就是調用了TCPServer的初始化函數__init__以及serve_forever(), 隨後調用的是子類的Request_handler函數

程式結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.