• socketserver,threading


    一,socketserver 

    #server
    import socketserver
    class Myserver(socketserver.BaseRequestHandler):
        def handle(self):
            self.data = self.request.recv(1024).strip()
            print("{} wrote:".format(self.client_address[0]))
            print(self.data)
            self.request.sendall(self.data.upper())
    
    if __name__ == "__main__":
        HOST, PORT = "127.0.0.1", 9999
    
        # 设置allow_reuse_address允许服务器重用地址
        socketserver.TCPServer.allow_reuse_address = True
        # 创建一个server, 将服务地址绑定到127.0.0.1:9999
        server = socketserver.TCPServer((HOST, PORT),Myserver)
        # 让server永远运行下去,除非强制停止程序
        server.serve_forever()
    # client 端
    import socket
    
    HOST, PORT = "127.0.0.1", 9999
    data = "hello"
    
    # 创建一个socket链接,SOCK_STREAM代表使用TCP协议
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((HOST, PORT))          # 链接到客户端
        sock.sendall(bytes(data + "
    ", "utf-8")) # 向服务端发送数据
        received = str(sock.recv(1024), "utf-8")# 从服务端接收数据
    
    print("Sent:     {}".format(data))
    print("Received: {}".format(received))

    二.threading

    线程初识

    import time
    import threading
    
    def task(a1,a2,a3):
        time.sleep(2)
        print('拿快递')
    
    def play():
        print('和女朋友去耍')
    
    def wm():
        print('去拿外卖')
    
    # 创建一个线程
    # 让该线程去执行任务:函数
    t1 = threading.Thread(target=task,args=(1,2,3,))
    # 去执行吧
    t1.start()
    
    # 创建一个线程
    # 让该线程去执行任务:函数
    t2 = threading.Thread(target=play)
    # 去执行吧
    t2.start()
    # 创建一个线程
    # 让该线程去执行任务:函数
    t3 = threading.Thread(target=wm)
    # 去执行吧
    t3.start()
    
    print('玩扇子')
    print('煽风点火')
    print('耍贱...')

    线程接收任务

    import time
    import threading
    def task(n):
        print('开始执行任务:',n)
        time.sleep(10)
        print('...')
        print('任务%s 执行完毕:'%n)
    
    while True:
        name = input("请输入任务:")
        t = threading.Thread(target=task,args=(name,))
        t.start()

    socket和线程配合

    import time
    import socket
    import threading
    
    def task(conn):
        time.sleep(20)
        data = conn.recv(1024)
        print(data)
        conn.close()
    
    
    server = socket.socket()
    server.bind(('192.168.13.84',8001,))
    server.listen(5)
    
    while True:
        conn,addr = server.accept()
        t = threading.Thread(target=task,args=(conn,))
        t.start()
  • 相关阅读:
    CentOS 7 配置hadoop(二) 配置hdfs(伪分布)
    CentOS 7 配置hadoop(一) 安装虚拟机(伪分布)
    linux配置
    hive配置
    引用的layui框架在网页上时间显示object
    Spring常用的基本注解
    5W1H分析法
    项目在网页中字符编码问题
    eclipse项目上如何传到码云上!
    spring+springmvc+mybatis+Redis的配置文件
  • 原文地址:https://www.cnblogs.com/zwq-/p/9601086.html
Copyright © 2020-2023  润新知