zoukankan      html  css  js  c++  java
  • Python:Day27 socketserver、线程

    socketserver模块源码中没找到get_request()的方法,原因????

    服务器端--------------------------------------------------
    import socketserver
    
    
    class MyServer(socketserver.BaseRequestHandler):    # 定义一个类,必须要继承括号中的类
        def handle(self):   # 这个方法名字只能是这个,因为父类中也有这个方法,此处是重写这个方法的。
            # while True:   #这个循环不要加,加了之后意外断开会出问题。
            conn = self.request
            while True:
                try:
                    data = conn.recv(1024)
                except Exception:
                    print("对方意外中断!")
                    break
                if not data:
                    break
                print(str(data, "utf8"))
                inp = input(">>>>:")
                conn.send(bytes(inp, "utf8"))
            conn.close()
    
    
    server1 = socketserver.ThreadingTCPServer(("127.0.0.1", 8000), MyServer)   # 此处容易忘记添加上面定义的类
    server1.serve_forever()
    
    
    
    客户端-------------------------------------------------------------
    import socket
    
    sk = socket.socket()
    ip_port = ("127.0.0.1",8000)
    sk.connect(ip_port)
    
    while True:
        inp = input(">>>>>:")
        if inp == "exit":
            break
        sk.send(bytes(inp, "utf8"))
        data = sk.recv(1024)
        print(str(data, "utf8"))
    sk.close()

    线程:

    计算密集型任务、I/O密集型的任务

    线程的两种创建方法:

    (1)实例化Thread类,传入函数:

    import threading
    
    
    def foo(num):
        print('this is thread %s' % num)
    
    
    t1 = threading.Thread(target=foo(1))
    t2 = threading.Thread(target=foo(2))
    t1.start()    # this is thread 1
    t2.start()    # this is thread 2
    print(t1.getName())    # Thread-1
    print(t2.getName())    # Thread-2

    (2)从Thread派生一个子类,创建这个子类的实例

    import threading
    
    
    class MyThread(threading.Thread):
        def __init__(self, num):
            threading.Thread.__init__(self)
            self.num = num
    
        def run(self):
            print("this is thread %s" % self.num)
    
    
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()    # this is thread 1
    t2.start()    # this is thread 2

    join():在子线程完成运行之前,这个子线程的父线程将一直被阻塞。

    import threading
    import time
    
    
    def music(func):
        for i in range(2):
            print("Begin listening to %s . %s" % (func, time.ctime()))
            time.sleep(1)
            print("end listening  %s" % time.ctime())
    
    
    def movie(func):
        for i in range(2):
            print("Begin watching %s  .  %s" % (func, time.ctime()))
            time.sleep(5)
            print("end watching %s" % time.ctime())
    
    
    threads = []
    t1 = threading.Thread(target=music, args=("七里香",))
    threads.append(t1)
    t2 = threading.Thread(target=movie, args=("阿甘正传",))
    threads.append(t2)
    
    if __name__ == '__main__':
        for t in threads:
            t.start()
        t.join()    # t2进程结束后,主线程才继续执行
        print("all over ..........%s" % time.ctime())

    setDaemon():将线程设置为守护线程,设置为守护线程的线程,它守护着主线程,主进程结束了,它也就结束了。

    import threading
    import time
    
    
    def music(func):
        for i in range(2):
            print("Begin listening to %s . %s" % (func, time.ctime()))
            time.sleep(1)
            print("end listening  %s" % time.ctime())
    
    
    def movie(func):
        for i in range(2):
            print("Begin watching %s  .  %s" % (func, time.ctime()))
            time.sleep(5)
            print("end watching %s" % time.ctime())
    
    
    threads = []
    t1 = threading.Thread(target=music, args=("七里香",))
    threads.append(t1)
    t2 = threading.Thread(target=movie, args=("阿甘正传",))
    threads.append(t2)
    
    if __name__ == '__main__':
        t2.setDaemon(True)  #将t2设置为守护线程,
        for t in threads:
            t.start()
        print("all over ..........%s" % time.ctime())

    Threading的其它方法:

    # threading.currentThread(): 返回当前的线程变量。
    # threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
    # threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
    # 除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
    # run(): 用以表示线程活动的方法。
    # start():启动线程活动。
    # join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
    # isAlive(): 返回线程是否活动的。
    # getName(): 返回线程名。
    # setName(): 设置线程名。
  • 相关阅读:
    extjs2.0
    抽象类和接口的选择
    获得汉字字符串的首字母
    快速找回桌面快捷方式
    vs2008破解90天限制
    SQL Server索引的使用和优化
    SQL Server 索引结构及其使用
    桥接模式(Bridge)体验
    vs2008 Working with jQuery
    利用索引来提高速度
  • 原文地址:https://www.cnblogs.com/sq5288/p/9328979.html
Copyright © 2011-2022 走看看