• socket多线程TCP和UDP


    1.server_tcp.py

    import logging
    from socketserver import BaseRequestHandler, TCPServer, UDPServer
    from threading import Thread
    
    logging.basicConfig(
        level=logging.INFO,  # 定义输出到文件的log级别,大于此级别的都被输出
        format='%(asctime)s  %(filename)s  %(levelname)s : %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %H:%M:%S',  # 时间
        filename="./server_tcp.log",
        filemode='a')  # 写入模式“w”或“a”
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s  %(filename)s  %(levelname)s : %(message)s')
    # 告诉handler使用这个格式
    console.setFormatter(formatter)
    # 为root logger添加handler
    logging.getLogger('').addHandler(console)
    
    
    class EchoHandler(BaseRequestHandler):
        def handle(self):
            while True:
                logging.info('Got connection from:{}'.format(self.client_address))
                msg = self.request.recv(8192).decode("utf-8").strip()
                if not msg:
                    break
                else:
                    # print("msg:{}".format(msg))
                    self.request.send(msg.encode("utf-8"))
    
    
    if __name__ == '__main__':
        # 服务端的ip地址
        server_ip = '0.0.0.0'
        # 服务端socket绑定的端口号
        server_port = 5554
        NWORKERS = 100
    
        serv = TCPServer((server_ip, server_port), EchoHandler, bind_and_activate=True)  # 绑定socket服务端所在ip和端口号  TCP
        for n in range(NWORKERS):
            t = Thread(target=serv.serve_forever)
            t.daemon = True
            t.start()
            serv.serve_forever()

    2.client_tcp.py

    import logging
    import time
    from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM
    
    logging.basicConfig(
        level=logging.INFO,  # 定义输出到文件的log级别,大于此级别的都被输出
        format='%(asctime)s  %(filename)s  %(levelname)s : %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %H:%M:%S',  # 时间
        filename="client_tcp.log",
        filemode='a')  # 写入模式“w”或“a”
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s  %(filename)s  %(levelname)s : %(message)s')
    # 告诉handler使用这个格式
    console.setFormatter(formatter)
    # 为root logger添加handler
    logging.getLogger('').addHandler(console)
    
    # 服务端的ip地址
    server_ip = "10.8.67.236"
    # server_ip = "192.168.104.150"
    # server_ip = "45.199.148.36"
    # server_ip = "192.168.104.150"
    # 服务端socket绑定的端口号
    server_port = 5554
    # 请求次数
    count = 10
    # 请求暂停时间
    time_sleep = 1
    # 字节B
    byte_count = 100
    
    if __name__ == '__main__':
        start_time = time.time()
        for i in range(count):
            str_msg = "a" * byte_count
            if str_msg != "":
                client = socket(AF_INET, SOCK_STREAM)
                client.connect((server_ip, server_port))
                for j in range(10):
                    bytes_msg = bytes(str_msg, encoding="utf-8")
                    client.send(bytes_msg)
                    data = client.recv(8192).decode("utf-8")
                    logging.info("-------{}:{}".format(j, data))
                    time.sleep(0.1)
                # time.sleep(time_sleep / 1000)
                client.close()
        logging.info("*" * 100)
        logging.info("总耗时时长:{}".format(str(time.time() - start_time)))

    3.server_udp.py

    import logging
    from socketserver import BaseRequestHandler, TCPServer, UDPServer
    from threading import Thread
    
    logging.basicConfig(
        level=logging.INFO,  # 定义输出到文件的log级别,大于此级别的都被输出
        format='%(asctime)s  %(filename)s  %(levelname)s : %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %H:%M:%S',  # 时间
        filename="./server.log",
        filemode='a')  # 写入模式“w”或“a”
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s  %(filename)s  %(levelname)s : %(message)s')
    # 告诉handler使用这个格式
    console.setFormatter(formatter)
    # 为root logger添加handler
    logging.getLogger('').addHandler(console)
    
    
    class EchoHandler(BaseRequestHandler):
        def handle(self):
            logging.info('Got connection from:{}'.format(self.client_address))
            data = self.request[0].strip()
            socket = self.request[1]
            socket.sendto(data, self.client_address)
    
    
    if __name__ == '__main__':
        # 服务端的ip地址
        server_ip = '192.168.61.205'
        # 服务端socket绑定的端口号
        server_port = 20000
        NWORKERS = 100
        # serv = TCPServer((server_ip, server_port), EchoHandler)  # 绑定socket服务端所在ip和端口号  TCP
        serv = UDPServer((server_ip, server_port), EchoHandler)  # 绑定socket服务端所在ip和端口号  UDP
        for n in range(NWORKERS):
            t = Thread(target=serv.serve_forever)
            t.daemon = True
            t.start()
            serv.serve_forever()
    

    4.client_udp.py

    import logging
    import time
    from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM
    
    logging.basicConfig(
        level=logging.INFO,  # 定义输出到文件的log级别,大于此级别的都被输出
        format='%(asctime)s  %(filename)s  %(levelname)s : %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %H:%M:%S',  # 时间
        filename="client_udp.log",
        filemode='a')  # 写入模式“w”或“a”
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    # 设置格式
    formatter = logging.Formatter('%(asctime)s  %(filename)s  %(levelname)s : %(message)s')
    # 告诉handler使用这个格式
    console.setFormatter(formatter)
    # 为root logger添加handler
    logging.getLogger('').addHandler(console)
    
    # 服务端的ip地址
    # server_ip = "10.8.67.236"
    server_ip = "192.168.104.150"
    # server_ip = "45.199.148.36"
    # 服务端socket绑定的端口号
    server_port = 6665
    # 请求次数
    count = 1
    # 请求暂停时间
    time_sleep = 1
    # 字节B
    byte_count = 100
    
    if __name__ == '__main__':
        start_time = time.time()
        for i in range(count):
            # str_msg = input("请输入要发送信息:")
            str_msg = "a" * byte_count
            if str_msg != "":
                bytes_msg = bytes(str_msg, encoding="utf-8")
                # client = socket(AF_INET, SOCK_STREAM)
                client = socket(AF_INET, SOCK_DGRAM)
                client.connect((server_ip, server_port))
                for i in range(100):
                    client.send(bytes_msg)
                    data = client.recv(8192).decode("utf-8")
                    logging.info("-------{}:{}".format(i, data))
                    time.sleep(1)
                time.sleep(time_sleep / 1000)
                client.close()
        logging.info("*" * 100)
        logging.info("总耗时时长:{}".format(str(time.time() - start_time)))
    

      

      

      

  • 相关阅读:
    kali linux 换国内源
    虚拟机桥接网络上网
    excel 无效引用 所引用的单元格不能位于256列
    sublime python配置运行
    java 环境变量配置(win10)
    Python错误:AssertionError: group argument must be None for now
    python if not
    ubuntu 安装mysql
    python 利用jieba库词频统计
    zxy的猪错误
  • 原文地址:https://www.cnblogs.com/yoyo1216/p/15090531.html
Copyright © 2020-2023  润新知