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,spindir 12 spinstr=‘.‘*spinpos+‘|‘+‘.‘*(spinsize-spinpos-1) 13 sys.stdout.write(‘\r‘+spinstr+‘ ‘) 14 sys.stdout.flush() 15 16 spinpos+=spindir 17 if spinpos<0: 18 spindir=1 19 spinpos=1 20 elif spinpos>=spinsize: 21 spinpos-=2 22 spindir=-1 23 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=sock.recv(4096).decode() 35 if not len(data): 36 print("\rRemote end closed connection; exiting.") 37 break 38 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 raise 17 except: 18 traceback.print_exc() 19 continue 20 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 break 29 time.sleep(2) 30 except (KeyboardInterrupt,SystemExit): 31 raise 32 except: 33 traceback.print_exc() 34 35 try: 36 clientsock.close() 37 except KeyboardInterrupt: 38 raise 39 except: 40 traceback.print_exc()
时间: 2024-11-08 21:33:46