python - 在python中将文件从客户端上传到服务器,反之亦然
问题描述
开始用 C++ 实现这个项目,但是我认为 Python 将是未来 x 平台的更好选择。
这里的目标是创建一个简单的文件服务器,然后创建一个客户端。客户端应该能够将文件上传到服务器并从服务器下载文件。
我的客户代码是:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
choice = raw_input("Upload or Download? (u/d):")
if choice == 'd':
filename = raw_input("File to Download? (q to quit): ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = long(data[6:])
message = raw_input("File found on the server!," +str(filesize)+"bytes, continue with download? y/n:")
if message == "y":
s.send('OK')
f = open('new_'+filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print ("Percentage Completed: "+"{0:.2f}".format((totalRecv/float(filesize))*100))
print ("File has been Downloaded!")
else:
print ("File doesnt exist!")
else:
filename = raw_input("File to Upload? (q to quit): ")
# if filename != 'q':
print ("Upload Function Coming Soon")
s.close()
if __name__ == '__main__':
Main()
服务器的代码是:
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS" + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR")
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print ("Server Started")
while True:
c, addr = s.accept()
print ("Client Connected:") + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("retrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
我已经很好地下载了文件,考虑一下,我应该能够对客户端的上传部分进行反向处理(而不是获取下载,我基本上复制服务器部分来执行上传) ...但是我似乎无法理解如何做到这一点。在这一点上,我并不担心硬编码端口等问题——稍后会解决这个问题,但是有人对此有任何建议吗?
我需要强调的是,我使用的是 python < v3(我知道它是旧的),但是它是我需要遵守的程序限制(因此 raw_input() v. input())
解决方案
推荐阅读
- parsing - 使用 Haskell 将随机嵌套列表展平为非嵌套列表
- c# - 如何从 sql 数据库中获取图像数据
- amazon-aurora - Amazon Aurora 预定活动
- python - 计算每行的列的平均值,不包括计算平均值的行
- rocket.chat - 如何添加自定义模型 Rocket Chat
- powershell - 通过 Powershell 设置邮箱文件夹权限失败
- java - OperationNotSupportedException:流结果(ResultSet)不支持操作
- android - Android:将 Media-Player App 设置为标准音乐播放器以捕捉外部媒体输入(NEXT SONG 等)
- java - 用于测试的fat jar 开源应用程序
- karate - 我们可以使用空手道将 PEM 文件转换为 jks 文件吗