Best Python code snippet using localstack_python
gbn.py
Source:gbn.py
1import config2import threading3import time4import udt5import util6# Go-Back-N reliable transport protocol.7class GoBackN:8 NO_PREV_ACK_MSG = (9 "Don't have previous ACK to send, will wait for server to timeout."10 )11 # "msg_handler" is used to deliver messages to application layer12 def __init__(self, local_port, remote_port, msg_handler):13 util.log("Starting up `Go Back N` protocol ... ")14 self.network_layer = udt.NetworkLayer(local_port, remote_port, self)15 self.msg_handler = msg_handler16 self.sender_base = 017 self.next_sequence_number = 018 self.set_timer()19 self.window = [b""] * config.WINDOW_SIZE20 self.expected_sequence_number = 021 self.receiver_last_ack = b""22 self.is_receiver = True23 self.sender_lock = threading.Lock()24 def set_timer(self):25 self.timer = threading.Timer((config.TIMEOUT_MSEC / 1000.0), self._timeout)26 # "send" is called by application. Return true on success, false otherwise.27 def send(self, msg):28 self.is_receiver = False29 if self.next_sequence_number < (self.sender_base + config.WINDOW_SIZE):30 threading.Thread(target=self._send_helper(msg))31 return True32 else:33 util.log("Window is full. App data rejected.")34 time.sleep(1)35 return False36 # Helper fn for thread to send the next packet37 def _send_helper(self, msg):38 self.sender_lock.acquire()39 packet = util.make_packet(msg, config.MSG_TYPE_DATA, self.next_sequence_number)40 packet_data = util.extract_data(packet)41 self.window[self.next_sequence_number % config.WINDOW_SIZE] = packet42 util.log("Sending data: " + util.pkt_to_string(packet_data))43 self.network_layer.send(packet)44 if self.sender_base == self.next_sequence_number:45 if self.timer.is_alive():46 self.timer.cancel()47 self.set_timer()48 self.timer.start()49 self.next_sequence_number += 150 self.sender_lock.release()51 return52 # "handler" to be called by network layer when packet is ready.53 def handle_arrival_msg(self):54 msg = self.network_layer.recv()55 msg_data = util.extract_data(msg)56 if msg_data.is_corrupt:57 if self.is_receiver:58 if self.expected_sequence_number == 0:59 util.log("Packet received is corrupted. " + self.NO_PREV_ACK_MSG)60 return61 self.network_layer.send(self.receiver_last_ack)62 util.log(63 "Received corrupted data. Resending ACK: "64 + util.pkt_to_string(util.extract_data(self.receiver_last_ack))65 )66 return67 # If ACK message, assume its for sender68 if msg_data.msg_type == config.MSG_TYPE_ACK:69 self.sender_lock.acquire()70 self.sender_base = msg_data.seq_num + 171 if self.sender_base == self.next_sequence_number:72 util.log(73 "Received ACK with seq # matching the end of the window: "74 + util.pkt_to_string(msg_data)75 + ". Cancelling timer."76 )77 self.timer.cancel()78 else:79 util.log(80 "Received ACK: "81 + util.pkt_to_string(msg_data)82 + ". There are messages in-flight. Restarting the timer."83 )84 if self.timer.is_alive():85 self.timer.cancel()86 self.set_timer()87 self.timer.start()88 self.sender_lock.release()89 # If DATA message, assume its for receiver90 else:91 assert msg_data.msg_type == config.MSG_TYPE_DATA92 util.log("Received DATA: " + util.pkt_to_string(msg_data))93 if msg_data.seq_num == self.expected_sequence_number:94 self.msg_handler(msg_data.payload)95 ack_pkt = util.make_packet(96 b"", config.MSG_TYPE_ACK, self.expected_sequence_number97 )98 self.network_layer.send(ack_pkt)99 self.receiver_last_ack = ack_pkt100 self.expected_sequence_number += 1101 util.log("Sent ACK: " + util.pkt_to_string(util.extract_data(ack_pkt)))102 else:103 if self.expected_sequence_number == 0:104 util.log("Packet received is out of order. " + self.NO_PREV_ACK_MSG)105 return106 util.log(107 "DATA message had unexpected sequence #"108 + str(int(msg_data.seq_num))109 + ". Resending ACK message with sequence # "110 + str(int(self.expected_sequence_number - 1))111 + "."112 )113 self.network_layer.send(self.receiver_last_ack)114 return115 # Cleanup resources.116 def shutdown(self):117 if not self.is_receiver:118 self._wait_for_last_ACK()119 if self.timer.is_alive():120 self.timer.cancel()121 util.log("Connection shutting down...")122 self.network_layer.shutdown()123 def _wait_for_last_ACK(self):124 while self.sender_base <= self.next_sequence_number - 1:125 util.log(126 "Waiting for last ACK from receiver with sequence # "127 + str(int(self.next_sequence_number - 1))128 + "."129 )130 time.sleep(1)131 def _timeout(self):132 util.log(133 "Timeout! Resending all packets in window. Resending packets with seq #s "134 + str(self.sender_base)135 + "-"136 + str(self.next_sequence_number - 1)137 + "."138 )139 self.sender_lock.acquire()140 if self.timer.is_alive():141 self.timer.cancel()142 self.set_timer()143 for i in range(self.sender_base, self.next_sequence_number):144 pkt = self.window[(i % config.WINDOW_SIZE)]145 self.network_layer.send(pkt)146 util.log("Resending packet: " + util.pkt_to_string(util.extract_data(pkt)))147 self.timer.start()148 self.sender_lock.release()...
receptor.py
Source:receptor.py
1import socket2import numpy as np # pip install numpy34socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)5transmissor = ("127.0.0.1", 2020)6receptor = ("127.0.0.1", 3030)7socketUDP.bind(receptor)8buff_size = 10000910next_sequence_number = 01112def verify_checksum(data):13 data_sum = np.uint16(0)14 for element in data:15 data_sum += element16 return data_sum == 0xFFFF1718def calculate_checksum(data):19 data_sum = np.uint16(0)20 for element in data:21 data_sum += element22 return np.invert(data_sum)2324def udt_send(packet):25 socketUDP.sendto(packet.tobytes(), transmissor)2627def rdt_rcv():28 while True:29 message, source = socketUDP.recvfrom(buff_size)30 if source == transmissor:31 return np.frombuffer(message, dtype=np.uint16)3233def make_pkt(Is_ACK,seq_num):34 sndpkt = np.array([], np.uint16)35 sndpkt = np.append(sndpkt, np.uint16(seq_num))36 sndpkt = np.append(sndpkt, np.uint16(0)) # checksum37 sndpkt = np.append(sndpkt, np.uint16(Is_ACK)) # is_ack3839 sndpkt[1] = calculate_checksum(sndpkt)40 return sndpkt4142if __name__ == "__main__":43 44 while True:45 sndpkt = []46 print("Waiting for Data...")47 rcvpkt = rdt_rcv()48 49 notcorrupt = verify_checksum(rcvpkt)50 haseq = rcvpkt[0] == next_sequence_number51 # print(f'Dados recebidos {rcvpkt}') 52 print("Não Está Corrompido?",notcorrupt) 53 print("Tem seq?",haseq) 54 if haseq:55 if notcorrupt:56 sndpkt = make_pkt(1,next_sequence_number)57 if next_sequence_number == 0:58 next_sequence_number = 159 else:60 next_sequence_number = 061 print(f'Dados recebidos {rcvpkt}') 62 else:63 sndpkt = make_pkt(0,next_sequence_number)64 if len(sndpkt) > 0:65 print("Dados Enviados ",sndpkt)66 udt_send(sndpkt)67686970
...
transmissor.py
Source:transmissor.py
1import socket2import numpy as np # pip install numpy345socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)6transmissor = ("127.0.0.1", 2020)7receptor = ("127.0.0.1", 3030)8socketUDP.bind(transmissor)9buff_size = 100001011next_sequence_number = 0121314def calculate_checksum(data):15 data_sum = np.uint16(0)16 for element in data:17 data_sum += element18 return np.invert(data_sum)192021def verify_checksum(data):22 data_sum = np.uint16(0)23 for element in data:24 data_sum += element25 return data_sum == 0xFFFF262728def udt_send(packet):29 socketUDP.sendto(packet.tobytes(), receptor)303132def rdt_rcv():33 while True:34 message, source = socketUDP.recvfrom(buff_size)35 if source == receptor:36 return np.frombuffer(message, dtype=np.uint16)373839def rdt_send(data):40 global next_sequence_number4142 sndpkt = np.array([], np.uint16)43 sndpkt = np.append(sndpkt, np.uint16(next_sequence_number))44 sndpkt = np.append(sndpkt, np.uint16(0)) # checksum45 sndpkt = np.concatenate((sndpkt, data))4647 sndpkt[1] = calculate_checksum(sndpkt)48 udt_send(sndpkt)4950 while True:51 rcvpkt = rdt_rcv()52 is_corrupt = not verify_checksum(rcvpkt)53 is_ack = rcvpkt[2] == True54 is_nack = rcvpkt[2] == False55 print("Dados recebidos ", rcvpkt)56 print("Está corrompido? ", is_corrupt)57 print("Está Nack? ", is_nack)58 print("Está Ack? ", is_ack)59 print("Seq Num? ", next_sequence_number)60 61 if is_corrupt or is_nack:62 udt_send(sndpkt)63 if is_ack and not is_corrupt:64 break6566 if next_sequence_number == 0:67 next_sequence_number = 168 else:69 next_sequence_number = 0707172if __name__ == "__main__":73 i = 174 while i <= 3:75 dados = np.random.randint(5, size=10, dtype=np.uint16)76 print(f'Dados a serem enviados {dados}')77 rdt_send(dados)
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!