1. 程式人生 > >網絡編程之socketserver

網絡編程之socketserver

有用 none select sockets read theme rom _屬性 bsp

網絡編程之socketserver
"""
socketserver.py 中的5個基礎類
        +------------+
        | BaseServer |
        +------------+
              |
              v
        +-----------+        +------------------+
        | TCPServer |------->| UnixStreamServer |
        +-----------+        +------------------+
              |
              v
        +-----------+        +--------------------+
        | UDPServer |------->| UnixDatagramServer |
        +-----------+        +--------------------+
"""

socketserver簡單概括 技術分享圖片
__version__ = "0.4"
import socket
import selectors
import os
import errno
import sys
try:
    import threading
except ImportError:
    import dummy_threading as threading
from io import BufferedIOBase
from time import monotonic as time

# __all__屬性由列表構成,它規定了模塊的所有可見方法,會使屬性列表之外的成員全部私有化。
__all__ = ["BaseServer", "TCPServer", "UDPServer", "ThreadingUDPServer", "ThreadingTCPServer", "BaseRequestHandler", "StreamRequestHandler", "DatagramRequestHandler", "ThreadingMixIn"] if hasattr(os, "fork"): __all__.extend(["ForkingUDPServer","ForkingTCPServer
", "ForkingMixIn"]) if hasattr(socket, "AF_UNIX"): # 如果socket類型是AF_UNIX則將下面的添加到列表中 __all__.extend(["UnixStreamServer","UnixDatagramServer", "ThreadingUnixStreamServer", "ThreadingUnixDatagramServer"]) if hasattr(selectors, PollSelector): _ServerSelector = selectors.PollSelector else: _ServerSelector = selectors.SelectSelector class BaseServer: # 基礎服務類 class TCPServer(BaseServer): # Tcp類 class UDPServer(TCPServer): # UDP類 if hasattr(os, "fork"): class ForkingMixIn: # 提供多進程功能的類 class ThreadingMixIn: # 提供多線程功能的類 if hasattr(os, "fork"): class ForkingUDPServer(ForkingMixIn, UDPServer): # UDP多進程類,實際就是繼承了ForkingMixIn和UDPServer而已 class ForkingTCPServer(ForkingMixIn, TCPServer): # TCP多進程類,實際就是繼承了ForkingMixIn和TCPServer而已 class ThreadingUDPServer(ThreadingMixIn, UDPServer): # UDP多線程類,實際就是繼承了ThreadingMixIn和UDPServer而已 class ThreadingTCPServer(ThreadingMixIn, TCPServer): # TCP多線程類,實際就是繼承了ThreadingMixIn和TCPServer而已 if hasattr(socket, AF_UNIX): # 如果你的socket是AF_UNIX族,則定義下面4個類 class UnixStreamServer(TCPServer): class UnixDatagramServer(UDPServer): class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): class BaseRequestHandler: # 業務邏輯類 class StreamRequestHandler(BaseRequestHandler): # TCP相關的業務邏輯 class _SocketWriter(BufferedIOBase): class DatagramRequestHandler(BaseRequestHandler): # UDP相關業務邏輯 """ 總結: socketserver.py 實際上就是封裝了TCP服務UDP服務,多線程TCP服務,多線程UDP服務,多進程TCP服務,多進程UDP服務的類 TCPServer(BaseServer) # TCP類 UDPServer(TCPServer) # UDP類 ForkingTCPServer(ForkingMixIn, TCPServer) # 多進程TCP類 ForkingUDPServer(ForkingMixIn, UDPServer) # 多進程UDP類 ThreadingTCPServer(ThreadingMixIn, TCPServer) # 多線程TCP類 ThreadingUDPServer(ThreadingMixIn, UDPServer) # 多線程UDP類 StreamRequestHandler(BaseRequestHandler): # TCP相關的業務邏輯 DatagramRequestHandler(BaseRequestHandler): # UDP相關業務邏輯 """
View Code

socketserver各個類之間的關系
#!/usr/bin/env python
# @Author   : "Wjl"
# @Date     : 2017/12/22
# @Time     : 15:12
# @SoftWare : PyCharm
# @File     : Test_Server.py

"""
通過下面的類創建基礎服務:
 如果是AF_INET                                                                           
 +-----------+        +------------------+        +--------------------+           
 | TCPServer |------->| ForkingTCPServer |   or   | ThreadingTCPServer |           
 +-----------+        +------------------+        +--------------------+           
 
 +-----------+        +------------------+        +--------------------+           
 | UDPServer |------->| ForkingUDPServer |   or   | ThreadingUDPServer |           
 +-----------+        +------------------+        +--------------------+

 如果是AF_UNIX
 +----------------+        +-------------------------+
 |UnixStreamServer|------->|ThreadingUnixStreamServer|
 +----------------+        +-------------------------+ 
  
 +------------------+        +---------------------------+ 
 |UnixDatagramServer|------->|ThreadingUnixDatagramServer|
 +------------------+        +---------------------------+

再將你的邏輯寫在如下類中的handle方法中(),傳遞給上面的類,來調用
 +--------------------+        +----------------------+        +------------------------+    
 | BaseRequestHandler |------->| StreamRequestHandler |   or   | DatagramRequestHandler |   
 +--------------------+        +----------------------+        +------------------------+ 

"""
import socketserver

class MyServer(socketserver.StreamRequestHandler):  # 繼承業務邏輯類
    def handle(self):  # 將你的業務邏輯寫在handle方法中
        print("服務端啟動...")
        while True:
            conn = self.request  # self.request就是客戶端的socket對象
            print(self.client_address)  # self.client_address就是客戶端地址元組
            while True:
                client_data = conn.recv(1024)
                print(str(client_data, "utf8"))
                print("waiting...")
                conn.sendall(client_data)
            conn.close()

if __name__ == __main__:
    server = socketserver.TCPServer((127.0.0.1, 8888), MyServer)  # 創建TCP服務,將業務邏輯傳遞給它,好讓服務和業務邏輯關聯起來
    server.serve_forever()  # 通過forever()方法來接收請求,其實就是調用了socket.accept方法
    # server.handle_request()  # 還可以調用handle_request()來處理請求

總結:

想要玩轉socketserver

1.首先需要明確使用什麽地址簇, 是 AF_INET還是UX_INET

2.明確是使用TCP還是UDP,以此來確定是使用哪個類

3.明確有沒有用到多線程或多進程

4.根據2來選擇對應的業務邏輯類來處理

網絡編程之socketserver