首页 > 代码库 > python-select异步IO

python-select异步IO

 1 #实现多任务在同一个线程切换 
 2 #!/usr/bin/python
 3 
 4 from socket import *
 5 from select import *
 6 from time import ctime
 7 
 8 sockob=socket(AF_INET,SOCK_STREAM)
 9 sockob.bind(("127.0.0.1",7777))
10 sockob.listen(5)
11 inputs=[sockob]
12 while 1:
13     rs,ws,es=select(inputs,[],[])
14     for i in rs:
15         if i==sockob:
16             connob,addr=sockob.accept()
17             print "connect from",addr
18             inputs.append(connob)
19         else:
20             try:
21                 data=http://www.mamicode.com/i.recv(1024)
22                 disconnect=not data
23             except:
24                 disconnect=True
25             if disconnect:
26                 print i.getpeername(),"disconnect"
27                 inputs.remove(i)
28                 i.close()
29             else:
30                 i.send("[%s]:%s"%(ctime(),data))
31 
32 sockob.close()

 

python-select异步IO