def connect(self, address: (str, int)): # client端 ,主动初始化TCP服务器连接,一般address的格式为元组(hostname, # port),如果连接出错,返回socket.error错误。 """ Connect to a remote socket at address. Corresponds to the process of establishing a connection on the client side. """ ############################################################################# # TODO: YOUR CODE HERE # ############################################################################# self.connectAddr = address self.sendto(segment(sin=1).getSegment(), self.connectAddr) # 发送请求连接报文 start_time = time.time() # 在收发的时候计算rtt # print("send connect request") data_sever, addr_sever = self.recvfrom(1024) # print("receive reply!") data_sever = segment.parse(data_sever) if data_sever.ack == 1 and data_sever.sin == 1: # and addr_sever == self.connectAddr: self.connectAddr = addr_sever # print("received ack") self.seqNum = 1 self.ackNum = data_sever.seqNumber + 1 self.RTT = time.time() - start_time # 初步计算出rtt的值 self.sendto(segment(ack=1, seqNumber=self.seqNum, ackNumber=self.ackNum).getSegment(), self.connectAddr) # print("send ack") self.status.append('connect') self.isConnected = True
def close(self): # 关闭套接字 """ Finish the connection and release resources. For simplicity, assume that after a socket is closed, neither futher sends nor receives are allowed. """ ############################################################################# # TODO: YOUR CODE HERE # ############################################################################# self.sendto(segment(fin=1).getSegment(), self.connectAddr) print('fin has been send') print('---------closed------------') # # initiative close # if 'client' in self.status: # self._send_to(segment(fin=1).getSegment()) # self._recv_from(1024) # self._recv_from(1024) # self._send_to(segment(ack=1).getSegment()) # # passivity close # else: # # TODO: passivity close # pass ############################################################################# # END OF YOUR CODE # ############################################################################# super().close()
def recv(self, bufsize: int) -> bytes: # 接收TCP数据,数据以字符串形式返回,bufsize指定要接收的最大数据量。flag提供有关消息的其他信息,通常可以忽略。 """ Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by bufsize. Note that ONLY data send by the peer should be accepted. In other words, if someone else sends data to you from another address, it MUST NOT affect the data returned by this function. """ data = b'' # assert self._recv_from, "Connection not established yet. Use recvfrom instead." ############################################################################# # TODO: YOUR CODE HERE # ############################################################################# rw = ReceiveWindow(windowSize=50, windowBase=0) # TODO 估计得改 while self.isConnected: data_sever, addr_sever = self.recvfrom(bufsize) data_sever = segment.parse(data_sever) print("recv:pkt", data_sever.seqNumber) if data_sever.Checksum(data_sever): # 若收到报文的checksum正确 if rw.addSegment(seqNum=data_sever.seqNumber, segment=data_sever): # 若报文正确添加进buffer中,回一个ack # print('recv: add segment successfully') self.sendto(segment(ackNumber=data_sever.seqNumber).getSegment(), self.connectAddr) print(f'recv: send ack {data_sever.seqNumber}, send rst {data_sever.rst}') elif rw.hasSegment(data_sever.seqNumber) or rw.checkFinish(data_sever.seqNumber): self.sendto(segment(ackNumber=data_sever.seqNumber).getSegment(), self.connectAddr) else: print('\033[31;42m recv: Wrong data occurs\033[0m') while rw.needCheck(): data = data + rw.checkBuffer().payload if data_sever.rst == 1 and data_sever.Checksum(data_sever): self.lastSegment = data_sever.seqNumber if rw.checkFinish(self.lastSegment) and self.lastSegment != 0: print('\033[31;42m recv: received all segments\033[0m') # for i in range(0, 10): # self.sendto(segment(rst=1).getSegment(), self.connectAddr) self.lastSegment = 0 break ############################################################################# # END OF YOUR CODE # ############################################################################# print(str(data)) return data
def slice_into_pieces(self, data: bytes, pieces_size): pieces = [] cnt = math.ceil(len(data) / pieces_size) for i in range(0, cnt + 1): # 最后一个包rst设为1,代表包发送完毕 header = segment(rst=1 if i == cnt else 0, seqNumber=i, ackNumber=self.ackNum, payload=data[pieces_size * i:min(pieces_size * (i + 1), len(data))]) pieces.append(header) return pieces
def ocr(image_arr): """ This function receives the url """ knn = cv2.KNearest() """ Training the KNN using Chars74k datatset. """ # Load the train data. ch74_labels, ch74_images = char74kdata(200) # Convert to numpy array form and flatten the images. train_labels = np.asarray(ch74_labels, dtype=np.float32) train_images = np.zeros([len(ch74_images), ch74_images[0].size], dtype=np.float32) for i in range(len(ch74_images)): train_images[i, :] = ch74_images[i].flatten() del ch74_images, ch74_labels # Train knn.train(train_images, train_labels) """ Running recognition session on a sample image. """ #image_path = 'sample9.png' #image_arr = cv2.imread(image_path, 0) #plt.imshow(image_arr) # Denoising image_denoised = denoise_median(image_arr) #plt.figure(); plt.imshow(image_denoised) image_bin = binarize_otsu(image_denoised) #plt.figure(); plt.imshow(image_bin) del image_arr, image_denoised forming_page = segment(image_bin) result = [] for i, line in enumerate(forming_page): letter_arr = line2arr(line) ret, resulting_labels, neighbours, dist = knn.find_nearest(letter_arr, k=10) line_text = [label2char(lbl) for lbl in resulting_labels] result.append(line_text) np.savetxt('OCRresult.txt', result, fmt='%s')
def accept(self) -> ('RDTSocket', (str, int)): # sever端,被动接受client端连接,非阻塞式等待连接的到来 """ Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. This function should be blocking. """ conn, addr = RDTSocket(self._rate), None ############################################################################# # TODO: YOUR CODE HERE # ############################################################################# while True: print("----- Server start listening -------") data_client, addr_client = self.recvfrom(1024) print("----- Server received -------") data_client = segment.parse(data_client) # 将受到的数据解码 if data_client.sin == 1: # 收到连接请求 conn.recvSin = True conn.ackNum = data_client.seqNumber + 1 # print("accept:receive connection request!") start_time = time.time() conn.sendto(segment(sin=1, ack=1, ackNumber=conn.ackNum).getSegment(), addr_client) # 发sin ack # print("accept:send sin ack") while True: data_client2, addr_client2 = conn.recvfrom(1024) self.RTT = time.time() - start_time # 初步确定RTT data_client2 = segment.parse(data_client2) # if data_client2.sin == 1 and data_client2.ack == 1 and addr_client2 == addr_client and data_client2.seqNumber == self.ackNum: # 收到了原来的地址发来的正确报文 if data_client2.ack == 1 and data_client2.seqNumber == conn.ackNum and addr_client2 == addr_client: # 收到了原来的地址发来的正确报文 conn.connectAddr = addr_client # 建立连接 conn.isConnected = True print("accept:connection established") conn.status.append('connect') self.reset() # 重置socket break break return conn, addr_client ############################################################################# # END OF YOUR CODE # ############################################################################# return conn, addr
ensure_directory(output_image_directory) # Preprocess image print("") print("Processing " + image) preprocessed_image = preprocess(image_name, output_image_directory, runmode=runmode) print("Finished preprocessing " + image) print(" **** ") # Segment preprocessed image print("Segmenting " + image) words_li_li = segment(preprocessed_image, output_image_directory, runmode=runmode) print("Finished segmenting " + image) print(" **** ") # Classify segmented image print("Classifying " + image) output_path = classify(output_image_directory, window_width=window_width, stepsize=stepsize, runmode=runmode) print("Finished classifying " + image) print("") print("Output is in: " + output_path) print("")
This file is intended only for runnning and testing The segmentation step. ''' image_name = "image.jpg" input_directory = "TestInputSegment" output_directory = "TestOutputSegment" input_image_name = os.path.join(input_directory, image_name) image = read_image (input_image_name) print ("") print ("Segmenting image " + image_name) print ("") words_li_li = segment(image, output_directory, runmode=2) print ("") print ("Finished Segmenting image " + image_name) print ("--------------------------------------------") number_lines = len(words_li_li) line_count = 0 print ("There are " + str(number_lines) + " lines, each having:") for words in words_li_li: line_count = line_count + 1 number_words = len(words) print ("Line " + str(line_count) + ": " + str(number_words) + " words")