1. 程式人生 > >TCP死鎖演示

TCP死鎖演示

pan .sh data socket argparse choices 解釋 utf num

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死鎖演示