输入/返回时,raw_input()不会停止通过键盘输入(输入)

时间:2018-09-23 03:22:44

标签: python sockets

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的新手,并使用套接字编写文件上传和下载服务。客户端程序要求用户键入操作名称以执行类似于“上传”的操作,以将文件上传到服务器,执行“下载”的操作,以从服务器下载文件。但是,client.py中第19行的raw_input()在按下带有操作名称的enter之后不会停止。 我在另一个终端(python 2.7)上执行 client.py 之前,在终端上的python 2.7上执行 server.py 。我不知道为什么我的代码卡在这里。有人可以告诉我哪里出了问题。预先谢谢你。

0 个答案:

没有答案