def receive(sock): totalRecv = 0 sizeToRead = 16 # 헤더의 크기 hBuffer = bytes() # 헤더 버퍼 # 헤더 읽기 # 첫 반복문에서는 스트림으로부터 메세지 헤더의 경계를 끊어냅니다. while sizeToRead > 0: buffer = sock.recv(sizeToRead) if not buffer: return None hBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) header = Header(hBuffer) totalRecv = 0 bBuffer = bytes() sizeToRead = header.BODYLEN # 첫 반복문에서 얻은 헤더는 본문의 길이를 뽑아내어 그 길이만큼 다시 스트림으로부터 본문을 읽습니다. while sizeToRead > 0: buffer = sock.recv(sizeToRead) if not buffer: return None bBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) body = None if header.MSGTYPE == message.REQ_FILE_SEND: body = BodyRequest(bBuffer) elif header.MSGTYPE == message.REP_FILE_SEND: body = BodyResponse(bBuffer) elif header.MSGTYPE == message.FILE_SEND_DATA: body = BodyData(bBuffer) elif header.MSGTYPE == message.FILE_SEND_RES: body = BodyResult(bBuffer) else: raise Exception("Unkonwn MSGTYPE : {0}".format(header.MSGTYPE)) msg = Message() msg.Header = header msg.Body = body return msg
def receive(sock): totalRecv = 0 sizeToRead = 16 # Header Size hBuffer = bytes() # Header Buffer # Read Header while sizeToRead > 0: # In the first loop, the boundary of the message header is cut from the stream. buffer = sock.recv(sizeToRead) if len(buffer) == 0: return None hBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) header = Header(hBuffer) totalRecv = 0 bBuffer = bytes() sizeToRead = header.BODYLEN while sizeToRead > 0: # Find out the length of the text in the header got from the first loop and read it back from the stream as long as it is. buffer = sock.recv(sizeToRead) if len(buffer) == 0: return None bBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) body = None if header.MSGTYPE == message.REQ_FILE_SEND: body = BodyRequest(bBuffer) elif header.MSGTYPE == message.REP_FILE_SEND: body = BodyResponse(bBuffer) elif header.MSGTYPE == message.FILE_SEND_DATA: body = BodyData(bBuffer) elif header.MSGTYPE == message.FILE_SEND_RES: body = BodyResult(bBuffer) else: raise Exception( "Unknown MSGTYPE : {0}". format(header.MSGTYPE)) msg = Message() msg.Header = header msg.Body = body return msg
def getBodyType(header, bBuffer): if header.MSGTYPE == message.REQ_FILE_SEND: print("BodyRequest") return BodyRequest(bBuffer) elif header.MSGTYPE == message.REP_FILE_SEND: print("BodyResponse") return BodyResponse(bBuffer) elif header.MSGTYPE == message.FILE_SEND_DATA: print("BodyData") return BodyData(bBuffer) elif header.MSGTYPE == message.FILE_SEND_RES: print("BodyResult") return BodyResult(bBuffer) else: raise Exception("Unknown MSGTYPE : {0}".format(header.MSGTYPE))
def receive(sock): totalRecv = 0 sizeToRead = 16 # 헤더의 크기 hBuffer = bytes() # 헤더 버퍼 # 헤더 읽기 while sizeToRead > 0: buffer = sock.recv(sizeToRead) if len(buffer) == 0: return None hBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) header = Header(hBuffer) totalRecv = 0 bBuffer = bytes() sizeToRead = header.BODYLEN while sizeToRead > 0: buffer = sock.recv(sizeToRead) if len(buffer) == 0: return None bBuffer += buffer totalRecv += len(buffer) sizeToRead -= len(buffer) body = None if header.MSGTYPE == message.REQ_FILE_SEND: body = BodyRequest(bBuffer) elif header.MSGTYPE == message.REP_FILE_SEND: body = BodyResponse(bBuffer) elif header.MSGTYPE == message.FILE_SEND_DATA: body = BodyData(bBuffer) elif header.MSGTYPE == message.FILE_SEND_RES: body = BodyResult(bBuffer) else: raise Exception("Unknown MSGTYPE : {0}".format(header.MSGTYPE)) msg = Message() msg.Header = header msg.Body = body return msg
with open(filepath, 'rb') as file: totalRead = 0 msgSeq = 0 fragmented = 0 if filesize < CHUNK_SIZE: fragmented = message.NOT_FRAGMENTED else: fragmented = message.FRAGEMENTED while totalRead < filesize: rbytes = file.read(CHUNK_SIZE) totalRead += len(rbytes) fileMsg = Message() fileMsg.Body = BodyData(rbytes) header = Header(None) header.MSGID = msgId header.MSGTYPE = message.FILE_SEND_DATA header.BODYLEN = fileMsg.Body.GetSize() header.FRAGMENTED = fragmented if totalRead < filesize: header.LASTMSG = message.NOT_LASTMSG else: header.LASTMSG = message.LASTMSG header.SEQ = msgSeq msgSeq += 1 fileMsg.Header = header
with open(os.path.relpath(filepath), 'rb') as file: # 서버에서 전송 요청을 수락했다면, 파일을 열어 서버로 보낼 준비를 한다. totalRead = 0 msgSeq = 0 # ushort fragmented = 0 # byte if filesize < CHUNK_SIZE: fragmented = message.NOT_FRAGMENTED else: fragmented = message.FRAGMENTED while totalRead < filesize: rbytes = file.read(CHUNK_SIZE) totalRead += len(rbytes) fileMsg = Message() fileMsg.Body = BodyData( rbytes) # 모든 파일의 내용이 전송될 때까지 파일을 0x03 메세지에 담아 서버로 보낸다. header = Header(None) header.MSGID = msgId header.MSGTYPE = message.FILE_SEND_DATA header.BODYLEN = fileMsg.Body.GetSize() header.FRAGMENTED = fragmented if totalRead < filesize: header.LASTMSG = message.NOT_LASTMSG else: header.LASTMSG = message.LASTMSG header.SEQ = msgSeq msgSeq += 1 fileMsg.Header = header
def clientStart(self, bindIP, bindPort, bindpath): global CHUNK_SIZE startIP = bindIP startPort = bindPort startPath = bindpath sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a TCP socket try: self.textLog.append('[-] Server: {0}:{1}\n'.format( startIP, startPort)) self.textLog.moveCursor(QTextCursor.End) sock.connect((startIP, startPort)) # Accept Connection Request msgId = 0 reqMsg = Message() filesize = os.path.getsize(startPath) reqMsg.Body = BodyRequest(None) reqMsg.Body.FILESIZE = filesize reqMsg.Body.FILENAME = os.path.basename(startPath) msgId += 1 reqMsg.Header = Header(None) reqMsg.Header.MSGID = msgId reqMsg.Header.MSGTYPE = message.REQ_FILE_SEND reqMsg.Header.BODYLEN = reqMsg.Body.GetSize() reqMsg.Header.FRAGMENTED = message.NOT_FRAGMENTED reqMsg.Header.LASTMSG = message.LASTMSG reqMsg.Header.SEQ = 0 MessageUtil.send( sock, reqMsg ) # Connect to the server, the client sends a file transfer request message. rspMsg = MessageUtil.receive( sock) # Receive a response from the server if rspMsg.Header.MSGTYPE != message.REP_FILE_SEND: self.textLog.append( 'This is not a normal server response.\n{0}\n'.format( rspMsg.Header.MSGTYPE)) self.textLog.moveCursor(QTextCursor.End) exit(0) if rspMsg.Body.RESPONSE == message.DENIED: self.textLog.append('The server refused to send the file.\n') self.textLog.moveCursor(QTextCursor.End) exit(0) with open( os.path.relpath(startPath), 'rb' ) as file: # Prepare to open the file and send it to the server. totalRead = 0 msgSeq = 0 # ushort fragmented = 0 # byte fragmentedCnt = 0 if filesize < CHUNK_SIZE: fragmented = message.NOT_FRAGMENTED else: fragmented = message.FRAGMENTED while totalRead < filesize: rbytes = file.read(CHUNK_SIZE) totalRead += len(rbytes) fileMsg = Message() fileMsg.Body = BodyData( rbytes) # Send the file to the server # in a 0x03 message before the transfer is complete. header = Header(None) header.MSGID = msgId header.MSGTYPE = message.FILE_SEND_DATA header.BODYLEN = fileMsg.Body.GetSize() header.FRAGMENTED = fragmented if totalRead < filesize: header.LASTMSG = message.NOT_LASTMSG else: header.LASTMSG = message.LASTMSG header.SEQ = msgSeq msgSeq += 1 fragmentedCnt += 1 fileMsg.Header = header MessageUtil.send(sock, fileMsg) self.textLog.append( '# Fragmented count: {0}'.format(fragmentedCnt)) self.textLog.moveCursor(QTextCursor.End) rstMsg = MessageUtil.receive( sock) # Get a receive to see if it's been sent properly result = rstMsg.Body self.textLog.append('File Receive Success: {0}\n'.format( result.RESULT == message.SUCCESS)) self.textLog.moveCursor(QTextCursor.End) except Exception as err: self.textLog.append('Exception has occurred.\n{0}\n'.format(err)) self.textLog.moveCursor(QTextCursor.End) sock.close() self.textLog.append('The client finished.\n') self.textLog.moveCursor(QTextCursor.End)
def sendImage(): filepath = "/home/pi/ABO2/image.jpg" #서버와 연결된 소켓 객체 생성 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: #서버 연결 요청 sock.connect(("192.168.0.57", 8080)) #요청메시지 생성 requestMsg = Message() filesize = os.path.getsize(filepath) #요청메시지 바디 생성 - 파일전송요청 객체 생성 requestMsg.Body = BodyRequest(None) requestMsg.Body.FILESIZE = filesize requestMsg.Body.FILENAME = filepath[filepath.rindex("/")+1:] #요청메시지 헤더 생성 requestMsg.Header = Header(None) requestMsg.Header.MSGID = 1 requestMsg.Header.MSGTYPE = message.REQ_FILE_SEND requestMsg.Header.BODYLEN = requestMsg.Body.GetSize() requestMsg.Header.FRAGMENTED = message.NOT_FRAGMENTED requestMsg.Header.LASTMSG = message.LASTMSG requestMsg.Header.SEQ = 0 #요청메시지 전송 MessageUtil.send(sock, requestMsg) #응답메시지 읽기 responseMsg = MessageUtil.receive(sock) if responseMsg.Header.MSGTYPE != message.REP_FILE_SEND: #파일응답코드가 아니면 종료 exit(0) if responseMsg.Body.RESPONSE ==message.DENIED: #서버가 거부하면 종료 exit(0) #파일 읽기 with open(filepath, "rb") as file: totalsize = 0 msgSEQ = 0 fragmented = 0 if filesize < 4096: #메시지분할여부 - 4096바이트 이상이면 분할 fragmented = message.NOT_FRAGMENTED else: fragmented = message.FRAGMENTED while totalsize<filesize: readBytes = file.read(4096) totalsize += len(readBytes) #파일전송메시지 생성 fileMsg = Message() #파일전송메시지 바디 생성 - 파일전송데이터 객체 생성 fileMsg.Body = BodyData(readBytes) #파일전송메시지 헤더 생성 fileMsg.Header = Header(None) fileMsg.Header.MSGID = 2 fileMsg.Header.MSGTYPE = message.FILE_SEND_DATA fileMsg.Header.BODYLEN = fileMsg.Body.GetSize() fileMsg.Header.FRAGMENTED = fragmented fileMsg.Header.SEQ = msgSEQ if totalsize < filesize: fileMsg.Header.LASTMSG = message.NOT_LASTMSG else: fileMsg.Header.LASTMSG = message.LASTMSG msgSEQ += 1 #메시지 번호 1증가 print("#", end="") #파일전송메시지 전송 MessageUtil.send(sock, fileMsg) #//end while #파일닫기 file.close() #//end with open print() golobal resultM resultM = str(sock.recv(1024), "utf-8") #결과메시지 읽기 resultMsg = MessageUtil.receive(sock) result = resultMsg.Body print("파일 전송 성공 : {0}".format(result.RESULT==message.SUCCESS)) except Exception as err: print("예외발생 : "+err, end="") #소켓닫기 sock.close() print("클라이언트를 종료합니다.") return resultM