程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Programming: socket to realize file transfer (simple version of file server)

編輯:Python

subject :

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

notes : The following code is implemented on a machine , If you want to work on different machines , Connect the client to the server IP Address changed to server's IP address ( Prerequisites : The server and client can ping through ).

Server-side code

# 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()

Client code :

#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()

Result display :

The initial state :

Operation process :

Server side :

client :

final result :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved