TCP死锁:
两个程序共享有限的资源,由于糟糕的计划,A程序只能等待B程序资源占用结束后才能使用资源,这种情况就是死锁(deadlock)
代码的解释明天给出
#!/usr/bin/env python3 #-*- encoding:utf8 -*- import argparse,sys,socket def server(host,port,bytecount): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) sock.bind((host,port)) sock.listen(5) print("listening at",sock.getsockname()) while True: sc,addr = sock.accept() print("Processing up to 1024 Bytes at a time from",addr) n = 0 while True: data = sc.recv(1024) if not data:break output = data.decode().upper().encode() sc.sendall(output) n += len(data) print(" %d Bytes process so far" %(n,),end='') sys.stdout.flush() sc.close() print("socket closed") def client(host,port,bytecount): sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) bytecount = (bytecount+15) // 16 * 16 message = ("capitalize this!").encode() print("sending",bytecount,"bytes of data , in chunks of 16 bytes") sock.connect((host,port)) sent = 0 while sent < bytecount: sock.sendall(message) sent+= len(message) print(" %d Bytes sent" %(sent,),end='') sys.stdout.flush() print() sock.shutdown(socket.SHUT_WR) print('receiving all the data the server sends back') received = 0 while True: data = sock.recv(42) if not received:print('The first data received says',repr(data)) if not data:break received += len(data) print(' %d Bytes received' %(received,),end='') print() sock.close() if __name__ == "__main__": choices = { "client":client, "server":server } parser = argparse.ArgumentParser(description='Get deadlocked over TCP') parser.add_argument('role',choices=choices,help='which role to play') parser.add_argument('host',help='interface the server listen it;''host the client to send') parser.add_argument('bytecount', type = int , nargs = "?" , default=16 , help='number of bytes for cleint to send (default 16)') parser.add_argument('-p', metavar='PORT' ,type=int , default=1060 , help='TCP PORT(default 1060)') args = parser.parse_args() function=choices[args.role] function(args.host, args.p , args.bytecount)