欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

socketserver

程序员文章站 2022-07-05 11:34:51
基于tcp的套接字,关键就是两个循环,一个链接循环,一个通信循环 socketserver模块中分两大类:server类(解决链接问题)和request类(解决通信问题) server类: request类: 继承关系: 以下述代码为例,分析socketserver源码: 查找属性的顺序:Threa ......

 基于tcp的套接字,关键就是两个循环,一个链接循环,一个通信循环

socketserver模块中分两大类:server类(解决链接问题)和request类(解决通信问题)

server类:

socketserver

request类:

socketserver

继承关系:

socketserver

socketserver

 

 socketserver

 

以下述代码为例,分析socketserver源码:

ftpserver=socketserver.ThreadingTCPServer(('127.0.0.1',8080),FtpServer)
ftpserver.serve_forever()

查找属性的顺序:ThreadingTCPServer->ThreadingMixIn->TCPServer->BaseServer

  1. 实例化得到ftpserver,先找类ThreadingTCPServer的__init__,在TCPServer中找到,进而执行server_bind,server_active
  2. 找ftpserver下的serve_forever,在BaseServer中找到,进而执行self._handle_request_noblock(),该方法同样是在BaseServer中
  3. 执行self._handle_request_noblock()进而执行request, client_address = self.get_request()(就是TCPServer中的self.socket.accept()),然后执行self.process_request(request, client_address)
  4. 在ThreadingMixIn中找到process_request,开启多线程应对并发,进而执行process_request_thread,执行self.finish_request(request, client_address)
  5. 上述四部分完成了链接循环,本部分开始进入处理通讯部分,在BaseServer中找到finish_request,触发我们自己定义的类的实例化,去找__init__方法,而我们自己定义的类没有该方法,则去它的父类也就是BaseRequestHandler中找....

源码分析总结:

基于tcp的socketserver我们自己定义的类中的

  1.   self.server即套接字对象
  2.   self.request即一个链接
  3.   self.client_address即客户端地址

基于udp的socketserver我们自己定义的类中的

  1.   self.request是一个元组(第一个元素是客户端发来的数据,第二部分是服务端的udp套接字对象),如(b'adsf', <socket.socket fd=200, family=AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>)
  2.   self.client_address即客户端地址
socketserver
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/05/04 15:11
# @Author  : MJay_Lee
# @File    : server.py
# @Contact : limengjiejj@hotmail.com

import socketserver

# 通信循环
class MytcpHandler(socketserver.BaseRequestHandler):
    def handle(self):
        print(self)
        print(self.request)
        while True:
            try:
                data = self.request.recv(1024)
                if not data: break
                self.request.send(data.upper())
            except ConnectionResetError:
                break
        self.request.close()

if __name__ == '__main__':
    # 接收连接,(来一个连接,就创造一个线程对象并调该对象下的handle方法去服务此客户)
    server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MytcpHandler)
    # print(server) # <socketserver.ThreadingTCPServer object at 0x000000132630C0B8>
    # print(server.server_address) # ('127.0.0.1', 8080)
    # print(server.RequestHandlerClass) # <class '__main__.MytcpHandler'>
    # print(server.socket) # <socket.socket fd=380, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080)>
    server.serve_forever()
基于TCP-服务端
socketserver
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/05/04 15:11
# @Author  : MJay_Lee
# @File    : client.py
# @Contact : limengjiejj@hotmail.com

import os
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',8080))

while True:
    msg = '%s is running' % os.getpid()
    client.send(msg.encode('utf-8'))
    reply_msg = client.recv(1024)
    print(reply_msg.decode('utf-8'))
基于TCP-客户端
socketserver
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/05/04 17:40
# @Author  : MJay_Lee
# @File    : server.py
# @Contact : limengjiejj@hotmail.com

import socketserver

# 通信循环
class MyudpHandler(socketserver.BaseRequestHandler):
    def handle(self):
        # print(self)
        # print(self.request)
        # 区别于tcp,此处self.request接收到的内容为元组
        # (b'4208 is running', <socket.socket fd=360, family=AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>)
        msg = self.request[0]
        print('client发送来的数据',msg.decode('utf-8'))
        self.request[1].sendto(msg.upper(),self.client_address)

if __name__ == '__main__':
    # 接收连接,(来一个连接,就创造一个线程对象并调该对象下的handle方法去服务此客户)
    server = socketserver.ThreadingUDPServer(('127.0.0.1', 8080), MyudpHandler)
    # print(server) # <socketserver.ThreadingUDPServer object at 0x00000021E29AA198>
    # print(server.server_address) # ('127.0.0.1', 8080)
    # print(server.RequestHandlerClass) # <class '__main__.MyudpHandler'>
    # print(server.socket) # <socket.socket fd=368, family=AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('127.0.0.1', 8080)>
    server.serve_forever()
基于UDP服务端
socketserver
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/05/04 17:41
# @Author  : MJay_Lee
# @File    : client.py
# @Contact : limengjiejj@hotmail.com

import os
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
client.connect(('127.0.0.1',8080))

while True:
    msg = '%s is running' % os.getpid()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
    reply_msg = client.recv(1024)
    print(reply_msg.decode('utf-8'))
基于UDP客户端