python实现并发服务器的几种方式

3.使用多进程和多线程的方式实现并发服务器

import socket
from multiprocessing import Process
from threading import Thread


def task(sock):
    while True:
        try:
            recv_data = sock.recv(1024)
            if recv_data:
                print('accept data:', recv_data.decode())
                sock.sendall(recv_data)
            else:
                break
        except ConnectionResetError as e:
            print('close connecting.', e)
            break
    sock.close()


def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', 8001))
    sock.listen(5)
    while True:
        conn, addr = sock.accept()
        print('Connected by:', addr)
        # Process(target=task, args=(conn, )).start()     # 使用多进程
        Thread(target=task, args=(conn, )).start()


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(socket库)