码迷,mamicode.com
首页 > 其他好文 > 详细

TCP死锁演示

时间:2017-06-25 10:17:12      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:parse   ber   style   div   break   argparse   get   choices   pytho   

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

标签:parse   ber   style   div   break   argparse   get   choices   pytho   

原文地址:http://www.cnblogs.com/alben-cisco/p/7075508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!