client.py:
#!/usr/bin/env python.
import socket
HOST = "127.0.0.1"
PORT = 10887
class client:
def main(self):
#create a socket and connect to the server
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
#choose the file you wanna tinker with
fileName = raw_input("Please enter the file name you wanna tinker with\n")
print('what do you wanna do with this file ?')
print('upload: Upload it to the server')
print('download: Download it to your system')
print('rename: Rename the file')
print('delete: Delete the file')
print("Enter a character in to select above options a,b,c,d.....and press enter")
x = raw_input("Enter the name of the operation to perform.....\nfor example type in upload and press enter")
x = str(x).strip()
if(x=="upload"):
c.transferFile(x,fileName,s)
elif(x=="download"):
c.downloadFile(x,fileName,s)
elif(x=="rename"):
fileName1 = input("Enter new name for the file.")
c.editFile(x,fileName,fileName1,s)
elif(x=="delete"):
c.deleteFile(x,fileName,s)
data = s.recv(4096)
print("data sent by server",data)
s.close()
#transferring file to the server
def transferFile(self,x,fileName,s):
string = ''
var = [x,fileName]
f = open("/Users/deekshithbucky/Downloads/"+fileName,"rb")
if not f:
print('file not found, please check the name of the file')
for line in f:
string = string + line
var.append(string)
#print(var)
s.sendall(str(var))
f.close()
#download a file from the server
def downloadFile(self,x,fileName,s):
var = [x,fileName]
f = open("/Users/deekshithbucky/Downloads/"+fileName,"wb")
print(var)
while True:
data = s.recv(4096)
if not data is None:
f.write(data)
f.close()
#edit the file on server
def editFile(self,x,fileName,fileName1,s):
var = [x,fileName,fileName1]
print(var)
s.send(str(var))
#delete the file from the server.
def deleteFile(self,x,fileName,s):
var = [x,fileName]
print(var)
s.send(str(var))
if __name__ == "__main__":
c = client()
c.main()
server.py:
#!/usr/bin/env python.
import socket
import threading
import thread
import os
from os import path
import ast
HOST = "127.0.0.1"
PORT = 10887
class server:
def main(self):
lock = threading.Lock()
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(10)
while True:
data = ''
var = []
conn,addr = s.accept()
print('connected by the user: ',addr)
lock.acquire()
while True:
data = data+conn.recv(4096)
if not data:
print('nothing is received.')
lock.release()
break
try:
var.append(ast.literal_eval(data))
print(var)
except ValueError:
print("The file transmitted by client is empty!")
x = str(var[0]).strip()
if(x=="upload"):
thread.start_new_thread(target=self.receiveFile,args=(var,conn,addr))
if(x=="download"):
thread.start_new_thread(target=self.sendFile,args=(var,conn,addr))
if(x=="rename"):
thread.start_new_thread(target=self.renameFile,args=(var,conn,addr))
if(x=="delete"):
thread.start_new_thread(target=self.deleteFile,args=(var,conn,addr))
conn.close()
lock.release()
s.close()
#receive a file.
def receiveFile(self,var,conn,addr):
f = open("/Library/WebServer/Users/user"+str(addr)+"/documents/"+var[1],"wb")
f.write(var[2])
print('writing data '+var[2]+' to the file '+f)
f.close()
#send a file.
def sendFile(self,var,conn,addr):
string = ''
try:
f = open("/Library/WebServer/Users/user"+"/documents/"+var[1],"rb")
for line in f:
string = string+line
conn.send(string)
f.close()
except:
print('could not open file.')
#rename a file on the Server.
def renameFile(self,var,conn,addr):
print('Renaming the file on Server....')
if path.exists(var[1]):
os.rename(var[1],var[2])
os.close()
conn.send("file renamed succesfully...")
#delete a file from the Server.
def deleteFile(self,var,conn,addr):
print('Deleting the file you want.....',addr)
fileName = var[1]
if os.path.exists(fileName):
os.remove(fileName)
os.close()
conn.send("file deleted succesfully.....")
else:
print('something is wrong')
if __name__ == "__main__":
s = server()
s.main()
Я новичок в python и пишу сервисы загрузки и выгрузки файлов с использованием сокетов.Клиентская программа просит пользователя ввести имя операции для выполнения операции «загрузить», чтобы загрузить файл на сервер, «загрузить», чтобы загрузить файл с сервера.Однако raw_input () в строке 19 в client.py не останавливается после нажатия клавиши enter с именем операции.Я выполняю server.py на python 2.7 в терминале, прежде чем выполнить client.py в другом терминале (python 2.7).Я не могу понять, почему мой код застрял здесь.Может кто-нибудь сказать мне, где это идет не так.Заранее спасибо.