python3 USES tcp to realize remote folder transmission
- 2020-11-20 06:10:21
- OfStack
This article shares the specific code of python remote folder transmission for your reference, the specific content is as follows
Functions:
The tcp protocol simulates the download of folders, but not files.
Let's implement the following:
Some of the features are not yet implemented and you can complete the code yourself if you're interested
Server-side code:
import os
import socket
import time
# Defines a global list to store subfolders
list1 = []
def deal_file(files,dir_name,dir_socket):
# If you open the file, you make an error files For the folder
try:
old_file = open(os.path.join(dir_name.decode(),files),"rb")
except:
# The folder that caused the error is put into the global list for processing
global list1
list1.append(files)
else:
# Read send close file is performed if no error is reported
file_data = old_file.read()
print(" Send content ")
dir_socket.send(file_data)
old_file.close()
def deal_dir():
# To be perfected for handling subfolders , It needs to be done recursively
pass
def main():
# Create the socket
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Fixed port number
tcp_socket.bind(("",9992))
# A passive socket converts to an active socket
tcp_socket.listen(128)
# Take the client out of the queue
dir_socket,client_ip = tcp_socket.accept()
# Accept client messages
dir_name = dir_socket.recv(1024)
# Display file list
file_list = os.listdir(dir_name.decode())
# Send the list of files to the client
dir_socket.send(str(file_list).encode())
# blocking 0.5s Waiting for sending successfully
time.sleep(0.5)
# Facilitate each file to send file content
for files in file_list:
deal_file(files, dir_name, dir_socket)
global list1
# If there are files in the global list
if list1:
# With perfect
pass
else:
dir_socket.close()
print(" All files have been transferred ")
tcp_socket.close()
if __name__ == '__main__':
main()
Client source code:
import socket
import os
import threading
import time
def recv_data(files,dir_name,tcp_socket):
file_data = tcp_socket.recv(1024)
new_file = open(os.path.join(dir_name+" new ", files),"wb")
new_file.write(file_data)
new_file.close()
print(" file %s The download is complete " % files)
def main():
# Create the socket
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Connect to server
tcp_socket.connect(("192.168.11.128", 9992))
# Sends the folder to copy to the server
dir_name = input(" Please enter the folder you want to copy ")
tcp_socket.send(dir_name.encode())
# New folder
os.mkdir(dir_name+" new ")
# List of accepted files , Loop open file write
file_list = tcp_socket.recv(1024)
a = eval(file_list)
print(a)
for files in eval(file_list.decode()):
recv_data(files,dir_name,tcp_socket)
if __name__ == '__main__':
main()