Based concurrency of socket programming socketserver

Based concurrency of socket programming socketserver

First, based on the TCP protocol

Based on tcp socket, the key is two cycles, a cycle link, a communication cycle

socketserver module carved into two categories: server class (link to solve the problem) and request class (to solve the communication problems)

1.1server class

[126- based socketserver socketserver class of concurrency .png? X-oss-process = style / watermark

1.2 request class

[126- socketserver based concurrency type of socket-request .png? X-oss-process = style / watermark

1.3 inheritance

[126- socket- inheritance socketserver concurrency based 1.png? X-oss-process = style / watermark

[126- socket- inheritance socketserver concurrency based 2.png? X-oss-process = style / watermark

[126- socket- inheritance socketserver concurrency based 3.png? X-oss-process = style / watermark

1.4 server

# 使用socketserver写服务端
# 导入模块
import socketserver

# 自己定义一个类, 必须继承BaseRequestHandler
class Mytcp(socketserver.BaseRequestHandler):
    # 必须要重写handle方法
    def handle(self):
        while True:  # 通信循坏
            print(self)

            # 给客户端回消息
            print(self.request)
            print(self.client_address)
            # 接收数据,  conn对象就是request
            data = self.request.recv(1024)
            print(data)
            if len(data) == 0:
                return
            # 发送数据
            self.request.send(b'234')


if __name__ == '__main__':
    # 实例化得到一个tcp连接对象, Threading意思是说,只要来了请求,他就自动开线程来处理连接跟交互数据
    # 第一个参数是绑定的地址, 第二个参数传一个类
    server = socketserver.ThreadingTCPServer(('127.0.0.1',8009), Mytcp)

    # 一直监听
    # 可以这么理解:只要来一个请求, 就起一个线程(连接一个人, 做交互)
    server.serve_forever()

1.5 Client

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080))  # 指定服务端ip和端口

while True:
    # msg=input('>>: ').strip() #msg=''
    msg = 'client33333'  # msg=''
    if len(msg) == 0: continue
    phone.send(msg.encode('utf-8'))
    data = phone.recv(1024)
    print(data)

phone.close()

1.6 Client 2

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080))  # 指定服务端ip和端口

while True:
    # msg=input('>>: ').strip() #msg=''
    msg = 'client11111'  # msg=''
    if len(msg) == 0: continue
    phone.send(msg.encode('utf-8'))
    data = phone.recv(1024)
    print(data)

phone.close()

Second, based on the UDP protocol

2.1 server

import socketserver

class MyUdp(socketserver.BaseRequestHandler):
    def handle(self):

        # print(self.request)
        # data=self.request[0]
        # print(data)
        data, addr  = self.request[1].recvfrom(1024)
        print(data)
        self.request[1].sendto('xxxx'.encode('utf-8'),addr)
        # self.request[1].sendto('xxxx'.encode('utf-8'),self.client_address)



        # while True:
        #     try:
        #         data = self.request.recvfrom(1024)
        #         print(data)
        #         # self.request.sendto(b'123')
        #
        #     except Exception as e:
        #         print(e)
        #         break

if __name__ == '__main__':
    server = socketserver.ThreadingUDPServer(('127.0.0.1', 8010), MyUdp)
    server.serve_forever()

2.2 Client 1


import socket

client=socket.socket(type=socket.SOCK_DGRAM)

client.sendto('randy'.encode('utf-8'),('127.0.0.1', 8010))
data = client.recvfrom(1024)
print(data)

2.3 Client 2

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # 数据报协议-》udp

while True:
    # msg=input('>>: ').strip() #msg=''
    msg = 'client2222'
    client.sendto(msg.encode('utf-8'), ('127.0.0.1', 8080))
    data, server_addr = client.recvfrom(1024)
    print(data)

client.close()

Three, socketserver source code analysis

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

Find the Order of Attributes: ThreadingTCPServer-> ThreadingMixIn-> TCPServer-> BaseServer

  1. Examples of ftpserver obtained, first find the class ThreadingTCPServer the __init__, found in the TCPServer thereby carry server_bind, serve6666666666666666665555555555555r_active
  2. Get serve_forever under ftpserver, BaseServer found, the execution further self._handle_request_noblock (), which is likewise in the BaseServer
  3. Performing self._handle_request_noblock () performs addition request, client_address = self.get_request ((TCPServer is in self.socket.accept ())), then perform self.process_request (request, client_address)
  4. Found in ThreadingMixIn process_request, open multiple threads to deal with concurrency, and then execute process_request_thread, execution self.finish_request (request, client_address)
  5. The four partially completed cycle links, this part of the communication processing section began to enter, find finish_request in BaseServer, the trigger our own set 6556
  6. 656565555555555555555 defined class is instantiated, go __init__ method, and our own definition of the class is not the way to go if its parent is in BaseRequestHandler find ....

3.1 source code analysis summary

Tcp-based class of socketserver our own definition of

  • self.server socket object that is
  • self.request that is a link
      
  • self.client_address namely client address

Udp-based class of socketserver our own definition of

  • self.request is a tuple (a first element is the data sent by the client, the server is a second portion of udp socket object), such as (b'adsf ', <socket.socket fd = 200, family = AddressFamily.AF_INET, type = SocketKind.SOCK_DGRAM, proto = 0, laddr = ( '127.0.0.1', 8080)>)
      
  • self.client_address namely client address

Guess you like

Origin www.cnblogs.com/randysun/p/11517086.html