Python solves sticky packet phenomenon (struct module)

Source: Internet
Author: User
Tags unpack

A. struct module

The module can convert a type to a fixed-length bytes

Import Structlst   = [1,2,4,3,5,]lst1  = [1,2,4,3,5,7,8,9= struct.pack ('i', Len (LST)) # Convert the length of the list to a fixed 4 byte b = Struct.pack('i', Len (lst1))Print  (A,len (a))print(B,len (b))

The type of the symbol and the length table after the conversion:

The struct module implements large file transfers:

#Server SideImportSocketImportstructImportJSONImportOssk=socket.socket () Sk.bind ('127.0.0.1', 8989) ) Sk.listen () conn,addr=sk.accept () len_dic= Struct.unpack ('I', CONN.RECV (4)) [0]#unpack accepts a tuple type, with an index of 0 being the length of the dictionaryStr_dic = Conn.recv (len_dic). Decode ('Utf-8')#To receive a dictionary as a string type based on the length of the dictionaryDIC = Json.loads (str_dic)#converts a dictionary of string types to a dictionary (dict)ifdic['opt'] =='Upload': Up_load='D:\a\b\c\\'+ Os.path.basename (dic['filename'])#Path Stitching    #up_load = os.path.join (' D:\a\b\c\\ ', os.path.basename (dic[' filename '))     whiledic['filesize'] >0:read_size= CONN.RECV (2048) with open (Os.path.abspath (up_load), mode='AB') as F1:f1.write (read_size) dic['filesize'] -=Len (read_size)ifdic['opt'] =='Download': Down_load='D:\a\b\c'conn.send (Json.dumps (Os.listdir (Down_load)). Encode ('Utf-8'))     while1: S= CONN.RECV (2048). Decode ('Utf-8') file= Os.path.abspath (down_load+'/'+s)Print(file)ifos.path.isdir (file): Dic1= {'Tybe':'dir'} len_dic1= Struct.pack ('I', Len (Json.dumps (DIC1))) Conn.send (Len_dic1+ Json.dumps (DIC1). Encode ('Utf-8') ) Conn.send (Json.dumps (os.listdir (file)). Encode ('Utf-8')) Down_load=os.path.abspath (file)Continue        elifos.path.isfile (file): Dic2= {'Tybe':'fil','down_size': Os.path.getsize (file)} Len_dic2= Struct.pack ('I', Len (Json.dumps (Dic2))) Conn.send (Len_dic2+ Json.dumps (dic2). Encode ('Utf-8')) with open (File,mode='RB') as F:down_size=os.path.getsize (file) whiledown_size:a= F.read (2048)                    Print(a)###########Conn.send (a) down_size-=Len (a) Break
#Client SideImportSocketImportstructImportOSImportJsonsk=socket.socket () Sk.connect ('127.0.0.1', 8989))defupload (): DiC= {'opt':'Upload','filename': None,'filesize': None} file= Input ('Please enter an absolute path to upload:') dic['filename'] =file dic['filesize'] =os.path.getsize (file) str_dic=json.dumps (DIC) Len_dic= Struct.pack ('I', Len (str_dic))#automatically converts the length of a dictionary to a length of 4 bytes typesSk.send (Len_dic + str_dic.encode ('Utf-8')) with open (dic['filename'],mode='RB') as F: whiledic['filesize'] >0:read_size= F.read (2048) sk.send (read_size) dic['filesize'] -=Len (read_size)defDownload (): DiC= {'opt':'Download','filename': None,'filesize': None} sk.send (Struct.pack ('I', Len (Json.dumps (DIC))) +json.dumps (DIC). Encode ('Utf-8'))     while1: LST= Json.loads (SK.RECV (2048). Decode ('Utf-8'))         forKvinchEnumerate (LST, 1):            Print(k, v) file= Input ('Please enter the file you want to download according to the serial number:') sk.send (lst[int (file)-1].encode ('Utf-8')) Len_dic= Struct.unpack ('I', SK.RECV (4)) [0] Str_dic= Sk.recv (Len_dic). Decode ('Utf-8')        ifJson.loads (Str_dic) ['Tybe'] =='dir':            Continue        elifJson.loads (Str_dic) ['Tybe'] =='fil': Down_file='D:\a\b\c\\'+lst[int (file)-1]             whileJson.loads (Str_dic) ['down_size']: With open (Down_file,mode='AB') as F:down_= SK.RECV (2048) F.write (down_) json.loads (str_dic) ['down_size'] -=Len (down_)if __name__=='__main__': LST= ['Upload','Download']    defmai (): forKvinchEnumerate (lst,1):            Print(k,v) C= Input ('Please enter the operation by ordinal:')        ifc = ='1': Upload ()ifc = ='2': Download ()Else:            Print('input Error!') mai ()

Python solves sticky packet phenomenon (struct module)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.