首页 > 代码库 > Python CODE——Nonblocking I/O client AND Delaying Server
Python CODE——Nonblocking I/O client AND Delaying Server
1 #!Nonblocking I/O - Chapter 5 -pollclient.py 2 import socket,sys,select 3 port=51423 4 host=‘localhost‘ 5 6 spinsize=10 7 spinpos=0 8 spindir=1 9 10 def spin():11 global spinsize,spinpos,spindir12 spinstr=‘.‘*spinpos+‘|‘+‘.‘*(spinsize-spinpos-1)13 sys.stdout.write(‘\r‘+spinstr+‘ ‘)14 sys.stdout.flush()15 16 spinpos+=spindir17 if spinpos<0:18 spindir=119 spinpos=120 elif spinpos>=spinsize:21 spinpos-=222 spindir=-123 24 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)25 sock.connect((host,port))26 27 p=select.poll()28 p.register(sock.fileno(),select.POLLIN|select.POLLERR|select.POLLHUP)29 30 while True:31 results=p.poll(2002)32 if len(results):33 if results[0][1]==select.POLLIN:34 data=http://www.mamicode.com/sock.recv(4096).decode()35 if not len(data):36 print("\rRemote end closed connection; exiting.")37 break38 sys.stdout.write("\rReceived :"+data)39 sys.stdout.flush()40 spin()41 else:42 print("\rProblem occurred; exiting")43 sys.exit(0)
1 #!Delaying Server - Chapter 5 -delayserver.py 2 import socket,traceback,time 3 4 host="" 5 port=51423 6 7 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) 8 sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 9 sock.bind((host,port))10 sock.listen(1)11 12 while True:13 try:14 clientsock,clientaddr= sock.accept()15 except KeyboardInterrupt:16 raise17 except:18 traceback.print_exc()19 continue20 21 try:22 print("Got connection from ",clientsock.getpeername)23 while True:24 try:25 print(time.asctime().encode())26 clientsock.sendall(time.asctime().encode()+b"\n")27 except:28 break29 time.sleep(2)30 except (KeyboardInterrupt,SystemExit):31 raise32 except:33 traceback.print_exc()34 35 try:36 clientsock.close()37 except KeyboardInterrupt:38 raise39 except:40 traceback.print_exc()
Python CODE——Nonblocking I/O client AND Delaying Server
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。