Python CODE——Nonblocking I/O client AND Delaying Server

 #!Nonblocking I/O - Chapter 5 -pollclient.py
import socket,sys,select
port=51423
host='localhost' spinsize=10
spinpos=0
spindir=1 def spin():
global spinsize,spinpos,spindir
spinstr='.'*spinpos+'|'+'.'*(spinsize-spinpos-1)
sys.stdout.write('\r'+spinstr+' ')
sys.stdout.flush() spinpos+=spindir
if spinpos<0:
spindir=1
spinpos=1
elif spinpos>=spinsize:
spinpos-=2
spindir=-1 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port)) p=select.poll()
p.register(sock.fileno(),select.POLLIN|select.POLLERR|select.POLLHUP) while True:
results=p.poll(2002)
if len(results):
if results[0][1]==select.POLLIN:
data=sock.recv(4096).decode()
if not len(data):
print("\rRemote end closed connection; exiting.")
break
sys.stdout.write("\rReceived :"+data)
sys.stdout.flush()
spin()
else:
print("\rProblem occurred; exiting")
sys.exit(0)
 #!Delaying Server - Chapter 5 -delayserver.py
import socket,traceback,time host=""
port=51423 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((host,port))
sock.listen(1) while True:
try:
clientsock,clientaddr= sock.accept()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue try:
print("Got connection from ",clientsock.getpeername)
while True:
try:
print(time.asctime().encode())
clientsock.sendall(time.asctime().encode()+b"\n")
except:
break
time.sleep(2)
except (KeyboardInterrupt,SystemExit):
raise
except:
traceback.print_exc() try:
clientsock.close()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
上一篇:「AH2017/HNOI2017」礼物


下一篇:HDU 1232 畅通工程(道路连接)(裸并查集)