1. 程式人生 > >網絡編程- 解決黏包現象方案二之struct模塊(七)

網絡編程- 解決黏包現象方案二之struct模塊(七)

ads size input load close pen socket server dump

server端

import json
import struct
import socket

sk = socket.socket()
sk.bind((‘127.0.0.1‘,8080))
sk.listen()

conn,addr = sk.accept()
dic_len = conn.recv(4) # 4個字節 數字的大小
dic_len = struct.unpack(‘i‘,dic_len)[0]
content = conn.recv(dic_len).decode(‘utf-8‘) # 70
content_dic = json.loads(content)
if content_dic[‘operate‘] == ‘upload‘:
with open(content_dic[‘filename‘],‘wb‘) as f:
while content_dic[‘filesize‘]:
file = conn.recv(1024)
f.write(file)
content_dic[‘filesize‘] -= len(file)
conn.close()
sk.close()

client端

import os
import json
import struct
import socket

sk = socket.socket()
sk.connect((‘127.0.0.1‘,8080))

def get_filename(file_path):
filename = os.path.basename(file_path)
return filename

#選擇 操作
operate = [‘upload‘,‘download‘]
for num,opt in enumerate(operate,1):
print(num,opt)
num = int(input(‘請輸入您要做的操作序號 : ‘))
if num == 1:
‘‘‘上傳操作‘‘‘
file_path = input(‘請輸入要上傳的文件路徑 : ‘)
file_size = os.path.getsize(file_path) # 獲取文件大小
file_name = get_filename(file_path)
dic = {‘operate‘: ‘upload‘, ‘filename‘: file_name,‘filesize‘:file_size}
str_dic = json.dumps(dic).encode(‘utf-8‘)
ret = struct.pack(‘i‘, len(str_dic)) # 將字典的大小轉換成一個定長(4)的bytes
sk.send(ret + str_dic)
with open(file_path,‘rb‘) as f:
while file_size:
content = f.read(1024)
sk.send(content)
file_size -= len(content)
elif num == 2:
‘‘‘下載操作‘‘‘
sk.close()

網絡編程- 解決黏包現象方案二之struct模塊(七)