TCP死锁演示
Posted alben-xue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TCP死锁演示相关的知识,希望对你有一定的参考价值。
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("\r %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("\r %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(‘\r %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)
以上是关于TCP死锁演示的主要内容,如果未能解决你的问题,请参考以下文章
Java TCP/IP Socket深入剖析socket——TCP通信中由于底层队列填满而造成的死锁问题(含代码)
用java多线程编写哲学家就餐程序 利用多线程技术编写哲学家就餐程序,使之在运行时能演示产生死锁的情况,