当前位置: 首页 > 工具软件 > SocketServer > 使用案例 >

Socketserver详解

燕正德
2023-12-01
Python3中的SocketServer
  socket并不能多并发,只能支持一个用户,socketserver 简化了编写网络服务程序的任务,socketserver是socket的在封装。socketserver在python2中为SocketServer,在python3种取消了首字母大写,改名为socketserver。socketserver中包含了两种类,一种为服务类(server class),一种为请求处理类(request handle class)。前者提供了许多方法:像绑定,监听,运行…… (也就是建立连接的过程) 后者则专注于如何处理用户所发送的数据(也就是事务逻辑)。一般情况下,所有的服务,都是先建立连接,也就是建立一个服务类的实例,然后开始处理用户请求,也就是建立一个请求处理类的实例。
 
socketserver一共有这么几种类型:
 
1. class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)
2. class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
3. class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
4. class socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate=True)
 
继承关系图:
+------------+
| BaseServer | 
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+
 
如何创建一个socketserver :
 
  1. First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests.   
  2. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class.
  3. Then call the handle_request() orserve_forever() method of the server object to process one or many requests.
  4. Finally, call server_close() to close the socket.
 
  1. 创建一个请求处理的类,并且这个类要继承  BaseRequestHandlerclass ,并且还要 重写父类里handle()方法;
注释:为什么要重写handle方法时加上while循环  
        handle方法默认结束后断开链接继续监听  
  2. 你必须实例化 TCPServer,并且传递server IP和你上面创建的请求处理类,给这个TCPServer;
  3. server.handle_requese()#只处理一个请求,server.server_forever()处理多个一个请求,永远执行
  4. 关闭连接server_close()
 
import socketserver
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        # 创建一个链接,继承于socketserver中的BaseRequestHandler类
        conn = self.request
        # 发送登录提示
        conn.sendall(b"Welcome to login...")
        print("Client connect...")
        while True:
            print("Waitting for recving message...")
            # 接收消息
            message = conn.recv(1024)
            print(message.decode('utf-8'))
            # 收到exit就退出
            if message == "exit":
                break
            # 回复消息
            data = input("Reply message:")
            # 发送消息
            conn.sendall(data.encode('utf-8'))
if __name__ == "__main__":
   # 实例化
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 999, ), MyServer)
    # 调用serve_forever方法
    server.serve_forever()
'''
def serve_forever(self, poll_interval=0.5):
    """
    Handle one request at a time until shutdown.
    Polls for shutdown every poll_interval seconds. Ignores
    self.timeout. If you need to do periodic tasks, do them in
    another thread.
    """
'''
multi_socketserver_client.py

# 就是一个简单的TCP客户端
import socket
sock = socket.socket()
# 连接服务端
sock.connect(('127.0.0.1', 999, ))
login = sock.recv(1024)
print(login.decode('utf-8'))
while True:
    message = input("Please input the message:").strip()
    if message == "exit":
        sock.sendall(b'exit')
        break
    else:
        sock.sendall(message.encode('utf-8'))
        print("Waitting for recving message...")
        data = sock.recv(1024)
        print(data.decode('utf-8'))
sock.close()

 

 
 

转载于:https://www.cnblogs.com/ellisonzhang/p/10430118.html

 类似资料: