#服务端 from socket import * from multiprocessing import Process import os def main(): # 服务端文件根目录 ROOT = os.path.dirname(os.path.abspath(__file__)) s = socket(AF_INET,SOCK_STREAM) #绑定ip和端口 s.bind(('172.16.11.100',9999)) #监听客户端的连接请求 s.listen(10) #连接循环 while True: print('waiting...') connect,address = s.accept() p = Process(target=talk,args=(connect,ROOT)) p.start() p.join() s.close() def talk(connect,ROOT): #通信循环 while True: #接收文件名和文件大小 data1 = connect.recv(1024) str1 = data1.decode('utf-8') filename,filesize = str1.split('|') fullname = os.path.join(ROOT,filename) with open(fullname,'ab') as f: has_recv = 0 while has_recv != int(filesize): # 接收文件数据 data2 = connect.recv(1024) f.write(data2) has_recv += len(data2) print(has_recv) else: connect.send('上传成功'.encode('utf-8')) if __name__ == '__main__': main() from socket import * import os c = socket(AF_INET,SOCK_STREAM) #连接到服务器 c.connect(('172.16.11.100',9999)) #客户端文件所在目录 ROOT = os.path.dirname(os.path.abspath(__file__)) while True: #提示用户输入要上传的文件名 name = input('>>>').strip() # 文件完整路径 fullname = os.path.join(ROOT, name) #判断文件是否存在 if os.path.exists(fullname): # 文件大小 file_size = os.path.getsize(fullname) # 将文件发送给服务器 file_info = '%s|%d' % (name, file_size) c.send(file_info.encode('utf-8')) #打开 with open(fullname,'rb') as f: #假设已经发送的字节数 has_sent = 0 while has_sent != file_size: #读取 data = f.read(1024) #发送 c.sendall(data) #递增 has_sent += len(data) # 接收服务器响应信息 print(has_sent) #接收服务上传成功消息 data2 = c.recv(1024) print(data2.decode('utf-8')) else: print('文件不存在') c.close()
仅供参考!