Ejemplo n.º 1
0
 def processRequest(self, connectionSocket, addr):
     dataRec = connectionSocket.recv(1024)
     header, msg = protocol.decodeMsg(dataRec.decode(
     ))  # get client's info, parse it to header and content
     # Main logic of the program, send different content to client according to client's requests
     if (header == protocol.HEAD_REQUEST):
         self.listFile(connectionSocket)
         connectionSocket.close()
     elif (header == protocol.HEAD_DOWNLOAD):
         filename = self.path + "/" + msg
         if os.path.isfile(filename):
             self.sendFile(connectionSocket, filename, addr)
         else:
             connectionSocket.send(
                 protocol.prepareMsg(protocol.HEAD_ERROR,
                                     "File Does Not Exist"))
             connectionSocket.close()
     elif (header == protocol.HEAD_UPLOAD):
         uploadFilename = self.path + "/" + msg
         self.receiveFile(connectionSocket, uploadFilename, addr)
     elif (header == protocol.HEAD_SENDCHAT):
         self.registerRecipient(
             msg, addr
         )  #register the recipient on the server.  This allows the server to retrieve that persons target IP and port later if they want to respond to a chat
         self.printChat(msg)
         connectionSocket.close()
     else:
         connectionSocket.send(
             protocol.prepareMsg(protocol.HEAD_ERROR, "Invalid Message"))
         connectionSocket.close()
Ejemplo n.º 2
0
 def start(self):
     serverPort = self.port
     serverSocket = socket(AF_INET, SOCK_STREAM)
     serverSocket.bind(('', serverPort))
     serverSocket.listen(20)
     print('The server is ready to receive')
     while True:
         connectionSocket, addr = serverSocket.accept()
         dataRec = connectionSocket.recv(1024)
         header, msg = protocol.decodeMsg(dataRec.decode())
         # get client's info, parse it to header and content
         # Main logic of the program, send different content to client according to client's requests
         if (header == protocol.HEAD_REQUEST):
             self.listFile(connectionSocket)
         elif (header == protocol.HEAD_DOWNLOAD):
             self.sendFile(connectionSocket, self.path + "/" + msg)
         elif (header == protocol.HEAD_CHAT):
             print(msg)
             message = (
                 input("Please enter a message to send back to client"))
             self.chat(connectionSocket, message)
         elif (header == protocol.HEAD_UPLOAD):
             self.receiveFile(connectionSocket, self.path + "/" + msg)
         else:
             connectionSocket.send(
                 protocol.prepareMsg(protocol.HEAD_ERROR,
                                     "Invalid Message"))
         connectionSocket.close()
Ejemplo n.º 3
0
 def getFileList(self):
     mySocket = self.connect()
     mySocket.send(protocol.prepareMsg(protocol.HEAD_REQUEST, " "))
     header, msg = protocol.decodeMsg(mySocket.recv(1024).decode())
     mySocket.close()
     if (header == protocol.HEAD_LIST):
         files = msg.split(",")
         self.fileList = []
         for f in files:
             self.fileList.append(f)
     else:
         print("Error: cannnot get file list!")
Ejemplo n.º 4
0
 def getUploadableFileList(self):
     mySocket = self.connect()
     mySocket.send(protocol.prepareMsg(protocol.HEAD_REQUEST, " "))
     header, msg = protocol.decodeMsg(mySocket.recv(1024).decode())
     mySocket.close()
     filesInUploadList = [
         f for f in os.listdir(self.uploadPath)
         if isfile(join(self.uploadPath, f))
     ]
     self.uploadList = []
     for f in filesInUploadList:
         self.uploadList.append(f)
Ejemplo n.º 5
0
 def chatListen(self):
     self.chatSocket.bind((self.clientName, int(self.clientPort)))
     self.chatSocket.listen(20)
     while True:
         connectionSocket, addr = self.chatSocket.accept()
         dataRec = connectionSocket.recv(1024)
         header, chat = protocol.decodeMsg(dataRec.decode())
         if (header == protocol.HEAD_RECEIVECHAT):
             print("\nServer responded at " + str(datetime.now()) +
                   " and said: " + chat)
         if (header == protocol.HEAD_TERMINATECHAT
             ):  #client requests that the chat thread should terminate
             break
Ejemplo n.º 6
0
 def getFileList(self):
     mySocket = self.connect(self.serverName, self.serverPort)
     if mySocket is None:
         return
     mySocket.send(protocol.prepareMsg(protocol.HEAD_REQUEST, " "))
     header, msg = protocol.decodeMsg(mySocket.recv(1024).decode())
     mySocket.close()
     if (header == protocol.HEAD_LIST):
         files = msg.split(",")
         self.fileList = []
         for f in files:
             self.fileList.append(f)
     else:
         print("Error: cannnot get file list, or server has no files.")
Ejemplo n.º 7
0
 def sendMsg(self):
     mySocket = self.connect()
     mySocket.send(protocol.prepareMsg(protocol.HEAD_MESGREQUEST, ' '))
     header, msg = protocol.decodeMsg(mySocket.recv(1024).decode())
     mySocket.close()
     print("Client connected")
     while not exit():
         try:
             msg = input()
             name = input()
             print(name + "me> " + msg)
             sys.stdout.flush()
             clientSocket = socket(AF_INET, SOCK_STREAM)
             clientSocket.connect((self.serverName, self.clientPort))
             clientSocket.send(msg.encode())
             clientSocket.close()
             if msg.upper() == 'QUIT':
                 exit()
         except:
             break
Ejemplo n.º 8
0
 def downloadFile(self, fileName):
     mySocket = self.connect(self.serverName, self.serverPort)
     if mySocket is None:  #If a socket could not be opened, leave gracefully
         return
     mySocket.send(protocol.prepareMsg(protocol.HEAD_DOWNLOAD, fileName))
     with open(self.localPath + "/" + fileName, 'wb') as f:
         print('file opened')
         data = mySocket.recv(1024)
         head, msg = protocol.decodeMsg(
             data.decode(errors="ignore")
         )  #ignore encoding errors.  This stream can contain either real data, or error messages, we want to decode the bytes to find errors, and if there are none, proceed.
         if head == "ERR":
             print(
                 fileName + " ran into a problem: " + msg
             )  #file download failed for some reason.  Output the server error to the client.
         else:
             f.write(data)
             while data:
                 #print('receiving data...')
                 data = mySocket.recv(1024)
                 #print('data=%s', (data))
                 f.write(data)  # write data to a file
             print(fileName + " has been downloaded!")
     mySocket.close()
Ejemplo n.º 9
0
 def receiveFile(self, serverSocket, fileName, addr):
     with open(fileName, 'wb') as f:
         increment = 0
         print("\n" + fileName + " has begun an upload from " +
               str(addr[0]) + " at " + str(datetime.now()) + "!")
         data = serverSocket.recv(1024)
         head, msg = protocol.decodeMsg(
             data.decode(errors="ignore")
         )  #ignore encoding errors.  This stream can contain either real data, or error messages, we want to decode the bytes to find errors, and if there are none, proceed.
         if head == "ERR":
             print(
                 fileName + " ran into a problem: " + msg
             )  #file upload failed for some reason.  Output the server error to the client.
         else:
             f.write(data)
             while data:
                 #print('receiving data ' + str(increment) + '...')
                 increment = increment + 1
                 data = serverSocket.recv(1024)
                 #print('data=%s', (data))
                 f.write(data)  # write data to a file
             print("\n" + fileName + " has been uploaded from " +
                   str(addr[0]) + " at " + str(datetime.now()) + "!")
     serverSocket.close()