server
import socketdef send_file_2_client(new_socket,new_addr): file_name = new_socket.recv(1024).decode('utf-8') print('客户端(%s)需要下载的文件是:%s'%(str(new_addr),file_name)) file_content = None try: f = open(file_name,'rb') file_content = f.read() f.close except Exception as e: print('没有找到客户端要下载的文件(%s)'%file_name) if file_content: new_socket.send(file_content)def main(): tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) tcp_socket.bind(('',8888)) tcp_socket.listen(128) while True: new_socket,new_addr = tcp_socket.accept() send_file_2_client(new_socket,new_addr) new_socket.close() tcp_socket.close()if __name__ == '__main__': main()
client
import socketdef main(): tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip = input('请输入对方IP:') port = int(input('请输入对方端口:')) tcp_socket.connect((ip,port)) file = input('请输入要下载的文件(包含后缀):') tcp_socket.send(file.encode('utf-8')) data = tcp_socket.recv(1024) if data: with open('[cp]'+file,'wb') as f: f.write(data) tcp_socket.close()if __name__ == '__main__': main()