def handshake(self): self.__conn.sendto( Packet(SYN, 0, address, port, None).to_bytes(), (self.__router_address, self.__router_port)) data, sender = self.__conn.recvfrom(MAX_LEN) packet = Packet.from_bytes(data) if packet.packet_type == SYN_ACK: response_packet = Packet(ACK, packet.seq_num + 1, packet.peer_ip_addr, packet.peer_port, None) self.__conn.sendto(response_packet.to_bytes(), (sender[0], sender[1]))
def accept(self): packet, sender = self.recv_packet() if packet.packet_type == SYN: response_packet = Packet(SYN_ACK, packet.seq_num + 1, packet.peer_ip_addr, packet.peer_port, None) self._conn.sendto(response_packet.to_bytes(), (sender[0], sender[1])) packet_ack, sender_ack = self.recv_packet() if packet_ack.packet_type == ACK: # Connection established connection = Connection(packet_ack.peer_ip_addr, packet_ack.peer_port, self) self._list_of_connections.append(connection) return connection, sender
def send_packet(self, packet: Packet): timeout = 5 max_tries = 5 count = 0 while count < max_tries: try: self.__conn.sendto(packet.to_bytes(), (self.__router_address, self.__router_port)) self.__conn.settimeout(timeout) response, sender = self.__conn.recvfrom(MAX_LEN) response_packet = Packet.from_bytes(response) while response_packet.packet_type != ACK: response, sender = self.__conn.recvfrom(MAX_LEN) response_packet = Packet.from_bytes(response) return packet, sender except socket.timeout: count += 1
def recv(self, buffer_size): from common.Packet import Packet data, sender = self.__receiver.get_connection().recvfrom(buffer_size) packet = Packet.from_bytes(data) return packet.payload
def create_packets(self, data: str): chunks = Sender.chunk_data(data.encode('utf-8'), MAX_LEN - MIN_LEN) for chunk in chunks: yield Packet(DATA, self._get_and_increment_sequence_number(), self.__address, self.__port, chunk)
def handle_data_packet(self, packet, sender): self._conn.sendto( Packet(ACK, 0, packet.peer_ip_addr, packet.peer_port, None).to_bytes(), sender)
def recv_packet(self): data, sender = self._conn.recvfrom(MAX_LEN) packet = Packet.from_bytes(data) return packet, sender