标签:
小知识点:
python中无块级作用域,python中是以函数为作用域
python的作用域在执行前就已经确定
import socketserver class MyClass(socketserver.BaseRequestHandler): def handle(self): pass obj = socketserver.ThreadingTCPServer(("127.0.0.1", 888), MyClass) # socketserver模块里面的ThreadingTCPServer这个类,传参数为一个元组和一个自定义的类 obj.serve_forever() ThreadingTCPServer中继承两个父类ThreadingMixIn, TCPServer ThreadingMixIn里面有两个方法process_request_thread,process_request 执行TCPServer里面的构造方法并且继承了BaseServer父类 import threading def f1(arg): print(arg) for i in range(10): t = threading.Thread(target=f1, args=(1111,)) t.start()
import socket import select sk = socket.socket() ip_address = ("127.0.0.1", 888,) sk.bind(ip_address) sk.listen(5) li = [sk] wi = [] msg = {} while True: r, w, e = select.select(li, wi, [], 1) print(len(li), len(r), len(wi), len(w)) for i in r: # for循环搞得假并发现象 if i == sk: conn, address = i.accept() li.append(conn) msg[i] = [] conn.sendall(bytes("hello", encoding="utf-8")) else: try: res = i.recv(1024) if not res: # 某些系统客户端断开会给服务器发送空消息 raise Exception(‘断开乱接‘) else: wi.append(i) msg[i].append(res) except Exception as ee: li.remove(i) for ii in w: rest = msg[ii] + bytes("我收到了", encoding="utf-8") ii.sendall(rest) wi.remove(ii)
import threading import time def f1(): time.sleep(1) print(123) t = threading.Thread(target=f1()) # t.start() t.setDaemon(False) print(‘我来了‘)
标签:
原文地址:http://www.cnblogs.com/pangzhi/p/5675264.html