OOP programming: python3 uses socket module to simulate TCP communication-multi-process multi-client connection

import socket
import threading
import os
from time import strftime

class TcptimeServer: ## Define a class named TcpTimeServer. Define the basic attributes of the class
    def __init __ (self, host = '', port = 21567):
        self.addr = (host, port)
        self.serv = socket.socket ()
        self.serv.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.serv.bind (self.addr)
        self.serv.listen (2)

    def tcp_work (self, cli_sock): ## Create an instance. tcp_work, used to perform operations to receive and send data
        while True:
            rdata = cli_sock.recv (1024)
            rdata = rdata.decode ('utf8')
            if rdata.strip () == 'quit':
                break
            print (rdata.strip ())
            sdata = '[% s]% s'% (strftime ('% H:% S:% M'), rdata)
            cli_sock.send (sdata.encode ('utf8'))
        cli_sock.close ()

    def tcp_connect (self): ## Create an instance. tcp_connect, used for the server to wait for the client to connect. The fork multi-process module is introduced here to determine that the main process closes the client connection, and the child process is closed
        while True:
            cli_sock, cli_addr = self.serv.accept () Close the server connection, and the main process is responsible for controlling the zombie process. The child process is responsible for calling the work instance for work. Finally, avoid the fork bomb, and close the
            pid after the child process is completed = os.fork ()
            if pid:
                cli_sock.close ()
                while True:
                    result = os.waitpid (-1, 1) [0]
                    if result == 0:
                        break
            else:
                self.serv.close ()
                self.tcp_work(cli_sock)
                exit()
        self.serv.close()

if __name__ == '__main__': ## Call Class
    T = TcptimeServer ()
    T.tcp_connect () ## Call an instance in the class. Complete the function.

Published 73 original articles · praised 4 · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_27592485/article/details/100768259