python tcp

参考链接:https://docs.python.org/3/library/socket.html

config:

from yacs.config import CfgNode as CN

config = CN()

config.server = CN()
config.server.port = 9999
config.server.ip = "127.0.0.1"

config.client = CN()
config.client.port = 8888
config.client.ip = "127.0.0.1"


server:

from socket import *
from config import config
import multiprocessing
import time


def server_listen():
    HOST = config.server.ip
    PORT = config.server.port
    BUFSIZ = 1024
    ADDRESS = (HOST, PORT)

    # 创建监听socket
    tcpServerSocket = socket(AF_INET, SOCK_STREAM)

    # 绑定IP地址和固定端口
    tcpServerSocket.bind(ADDRESS)
    print("服务器启动,监听端口{}...".format(ADDRESS[1]))

    tcpServerSocket.listen(0)

    process_list = []
    try:
        while True:
            # print('服务器正在运行,等待客户端连接...')
            # client_socket是专为这个客户端服务的socket,client_address是包含客户端IP和端口的元组
            client_socket, client_address = tcpServerSocket.accept()
            # print('客户端{}已连接!'.format(client_address))
            p = multiprocessing.Process(target=server_accept, args=(client_socket, client_address))  # 参数与threading.Thread 一致,如果要传参数(args=(xxx))
            p.daemon = True  # 这个属性默认为False, 相当于主程序会等待子进程结束;设置True之后,子进程是一个后台进程
            p.start()
            process_list.append(p)
            process_list_number = len(process_list)
            i = 0
            while i < process_list_number:
                if process_list[i].is_alive() == False:
                    process_list.__delitem__(i)
                    i = 0
                    process_list_number = len(process_list)
                else:
                    i += 1
            time.sleep(1)
    finally:
        # 关闭监听socket,不再响应其它客户端连接
        for i in range(len(process_list)):
            process_list[i].join()
        tcpServerSocket.close()

def server_accept(client_socket, client_address):
    try:
        while True:
            # 接收客户端发来的数据,阻塞,直到有数据到来
            # 事实上,除非当前客户端关闭后,才会跳转到外层的while循环,即一次只能服务一个客户
            # 如果客户端关闭了连接,data是空字符串
            data = client_socket.recv(2048)
            if data:
                print('接收到消息 {}({} bytes) 来自 {}'.format(data.decode('utf-8'), len(data), client_address))
                # 返回响应数据,将客户端发送来的数据原样返回
                client_socket.send("ok".encode('utf-8'))
            else:
                # print('客户端 {} 已断开!'.format(client_address))
                break
    finally:
        # 关闭为这个客户端服务的socket
        client_socket.close()



if __name__ == '__main__':
    server_listen()

client:

from socket import *
from config import config
import multiprocessing



def client(client_no):
    HOST = config.server.ip
    PORT = config.server.port
    BUFSIZ = 1024
    ADDRESS = (HOST, PORT)

    tcpClientSocket = socket(AF_INET, SOCK_STREAM)
    try:
        tcpClientSocket.connect(ADDRESS)
        data = "client{0}".format(client_no)
        # 发送数据
        tcpClientSocket.send(data.encode('utf-8'))
        # 接收数据
        data, ADDR = tcpClientSocket.recvfrom(BUFSIZ)
        if data:
            print("服务器端响应:", data.decode('utf-8'))
    except:
        print("client connect failed!")
    tcpClientSocket.close()

if __name__ == '__main__':

    process_list = []

    process_number = 10
    for i in range(process_number):
        p = multiprocessing.Process(target=client, args=(i,))
        p.start()
        process_list.append(p)

    for i in range(process_number):
        process_list[i].join()

文章目录