-
Here is the text of the column by tcp file transfers, use struct module package to solve the sticky problem
# server端
importsocket
importjson
importstruct
sk= socket.socket()
sk.bind(('127.0.0.1', 9000))
sk.listen()
conn, addr= sk.accept()
msg_len= conn.recv(4) # b'"\x00\x00\x00'
dic_len= struct.unpack('i', msg_len)[0] # int类型
msg= conn.recv(dic_len).decode('utf-8')
msg= json.loads(msg)
withopen(msg['filename'], 'wb') asf:
whilemsg['filesize'] >0:
content= conn.recv(1024)
msg['filesize'] -= len(content)
f.write(content)
conn.close()
sk.close()
# client端
importsocket
importos
importjson
importstruct
sk= socket.socket()
sk.connect(('127.0.0.1', 9000)) abs_path with = 'you want to transfer the absolute path of the file to the server side' R & lt filename = OS. Path. The basename ( abs_path with) filesize = OS. Path. GetSize ( abs_path with) DIC = { 'filename': filename, ' filesize ': filesize} str_dic = . JSON dumps ( DIC) b_dic = str_dic. encode ( ' UTF-. 8 ') MLEN = struct. Pack ( ' I ', len ( b_dic)) SK. Send ( MLEN) SK. Send ( b_dic) with Open ( abs_path,
mode='rb') asf:
whilefilesize>0:
content= f.read(1024)
filesize-= len(content)
sk.send(content)
sk.close()
Stick package to solve the problem custom protocol tcp protocol
Guess you like
Origin www.cnblogs.com/he-qing-qing/p/11005995.html
Recommended
Ranking