所以,我正在我的计算机科学课中制作一些东西,你可以将文件发送到远程服务器并且可以正常工作,但是无法将它们收回。 SERVER.PY
import socket # Import socket module
import os #imports os module
def RecvFile():
while True: # allows it to always save files and not have to be restarted.
c, addr = s.accept()
print ('Connection Accepted From',addr)# this prints out connection and port
print ("File is comming ....")
file = c.recv(1024) #recieves file name from client
f = open(file,'wb') #open that file or create one
l = c.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(1024) #get again until done
print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
f.close()
def SendFile():
c, addr = s.accept()
print("Connection Accepted From",addr)
filename = c.recv(1024)
if os.path.isfile(filename):
s.send("EXISTS"+str(os.pthat.getsize(filename)))
response = c.recv(1024)
if response[:2] == 'OK':
with open(filename, 'rb') as f:
s.sendall(f.read)
f.close()
else:
s.send("ERR")
s.close()
def main():
s = socket.socket()
s.bind(('139.59.173.187', 8000)) # Binds port and IP address
s.listen(3)
print("Server Started")
while True:
c, addr = s.accept()
option = c.recv(1024)
if option == "S":
RecvFile()
elif option == "R":
SendFile()
else:
s.send("Incorrect input".encode('utf-8'))
main()
#if errors occur
c.close()
我认为server.py是问题
客户.py
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('139.59.173.187',8000))
print("=========================Welcome to the File System =========================")
option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
if option == "S" or option == "s":
s.send("S".encode('utf-8'))
file_name = input("Please input the file name\n>>>")
name = input("What would you like it to be saved as?\n>>>")
s.send(name.encode('utf-8'))
with open(file_name,'rb') as f:
s.sendall(f.read())
print("File has been sent to the server")
main()
elif option == "R" or option == "r":
s.send("R".encode('utf-8'))
filename = input("What is the filename you wish to recieve\n>>>")
s.send(filename.encode('utf-8'))
print ("File is comming ....")
f = open(filename,'wb') #open that file or create one
l = c.recv(1024) #now recieves the contents of the file
while (l):
print ("Receiving...File Data")
f.write(l) #save input to file
l = c.recv(1024) #get again until done
print("The file",filename,"has been succesfully saved to your computer")
f.close()
我已经花了7个小时来学习这个并且周五到期了。而不是说代码可以评论它的工作原理等。
答案 0 :(得分:0)
在server.py中,SendFile
和RecvFile
都使用他们无权访问的套接字对象s
。我建议您将其作为参数传递:
def RecvFile(s):
#...
def SendFile(s):
#...
然后在主要:
if option == "S":
RecvFile(s)
elif option == "R":
SendFile(s)