Pythonsocket上传和下载文件
服务端:
import socket ,os,json
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('',9999))
server.listen(5)
while True:
conn,addr = server.accept()
print('conn is addr :',addr)
while True:
cmd_obj = conn.recv(1024).decode()
print('cmd_obj=%s'%cmd_obj)
if not cmd_obj:break
if cmd_obj == 'get':
filename = r'D:\\IStudy\\Oracle\\1.jpg'
basefilename = os.path.basename(filename)
myfile = open(filename,'rb')
myfile_size = os.path.getsize(filename)
print(basefilename)
data = {'filename':basefilename,'filesize':myfile_size}
json_obj = json.dumps(data)
conn.send(json_obj.encode())
for readline in myfile:
conn.send(readline)
else:
conn.send(b'finish')
print('file send is finish')
客户端:
import socket,json
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('127.0.0.1',9999))
while True:
data = input('>>')
client.send(data.encode())
json_obj = client.recv(1024).decode()
file_info = json.loads(json_obj)
filename = file_info['filename']
filesize = file_info['filesize']
print('filename=',filename,'filesize=',filesize)
recevie_size = 0
myfile = open(filename,'wb')
while recevie_size < filesize:
filedata = client.recv(1024)
myfile.write(filedata)
recevie_size += len(filedata)
else:
myfile.close()
print('receive file finished!')