Use socket Programming a simple file server . Client program implementation put function ( Will a Files are transferred locally to the file server ) and get function ( Get a remote file from the file server and save it locally file ) . The client and file server are not on the same machine .
Customer downloads files :get file name Such as :get file1.txt
Customer uploads file :put file name Such as :put file2.txt
# encoding=utf-8
# Server side
import socket
import os
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 9000)) # Bind listener port
server.listen(5) # monitor
dirPath = 'F:\\fileServer\\'; # File server location
print(" The server is running ···")
while True:
conn, addr = server.accept() # Waiting for the connection
print('client addr:', addr) # conn Connect to the client
while True:
data = conn.recv(1024) # receive
if not data: # Client disconnected
print(' Client disconnected ')
break
print(' Orders received :', data.decode("utf-8"))
op = ''
try:
op, filename = data.decode('utf-8').split(' ')
filePath = dirPath + filename
except :
print(' Input has nothing to do with file operations ')
# Customer download task
if op == 'get':
if os.path.isfile(filePath): # Judge that the file exists
# 1. Send file size first , Make the client ready to receive
size = os.stat(filePath).st_size # Get file size
conn.send(str(size).encode('utf-8')) # Send data length
print(' The size of the transmission :', size)
# 2. Send file content
conn.recv(1024) # Receive confirmation
f = open(filePath, 'rb')
for line in f:
conn.send(line) # send data
f.close()
else: # The file does not exist
conn.send(' file does not exist '.encode("utf-8"))
# The customer uploads the task
if op == 'put':
# 1. Receive file length first
server_response = conn.recv(1024)
file_size = int(server_response.decode("utf-8"))
print(' Received size :', file_size)
# 2. Receive file content
filename = 'new' + filename
filePath = dirPath + filename
f = open(filePath, 'wb')
received_size = 0
while received_size < file_size:
size = 0 # Accurate received data size , Solve the sticky package
if file_size - received_size > 1024: # Receive multiple times
size = 1024
else: # Last received
size = file_size - received_size
filedata = conn.recv(size) # Receive content multiple times , Receiving big data
filedata_len = len(data)
received_size += filedata_len
print(' Received :', int(received_size / file_size * 100), "%")
f.write(filedata)
f.close()
server.close()
#encoding=utf-8
import socket
import os
client = socket.socket() # Generate socket Connection object
ip_port = ('127.0.0.1', 9000) # Address and port number
try:
client.connect(ip_port) # Connect
print(' Server connected ')
except :
print(' Server connection failed , Please re run after modification !!')
exit(0)
while True:
#content = input(">>")
content = input(' Please enter the file operation you want to perform :')
if content=='exit': # Exit operation
exit(1)
client.send(content.encode())
if len(content) == 0: # If you pass in a null character, continue
continue
if content.startswith("get"): # Download task
client.send(content.encode("utf-8")) # Both transmission and reception are bytes type
# 1. Receive length first , If the receiving length is wrong , Description file does not exist
server_response = client.recv(1024)
try:
file_size = int(server_response.decode("utf-8"))
except:
print(' file does not exist ')
continue
print(' Received size :', file_size)
# 2. Receive file content
filename = 'new' + content.split(' ')[1]
f = open(filename, 'wb')
received_size = 0
while received_size < file_size:
size = 0 # Accurate received data size , Solve the sticky package
if file_size - received_size > 1024: # Receive multiple times
size = 1024
else: # Last received
size = file_size - received_size
data = client.recv(size) # Receive content multiple times , Receiving big data
data_len = len(data)
received_size += data_len
print(' Received :', int(received_size / file_size * 100), "%")
f.write(data)
f.close()
elif content.startswith('put'): # Upload task
op, filename = content.split(" ")
if os.path.isfile(filename): # Judge that the file exists
# 1. Send file size first , Make the client ready to receive
size = os.stat(filename).st_size # Get file size
client.send(str(size).encode("utf-8")) # Send data length
print(' The size of the transmission :', size)
# 2. Send file content
f = open(filename, 'rb')
for line in f:
client.send(line) # send data
f.close()
else: # The file does not exist
print(' file does not exist ') # Send data length
f.close()
else:
pass
client.close()
Server side :
client :