TB067

Apuntes y Resueltos de la Materia Redes de Comunicaciones (TB067)
Index Commits Files Refs README
commit ac113cca41353165166aa38ddf9c40f344471779
parent 1ccf97fde546840864f419a4d082811ea3c82fcb
Author: Martin Kloeckner <mjkloeckner@gmail.com>
Date:   Fri, 27 Sep 2024 11:15:41 -0300

added `tps/2C2024/1/scripts/`

Diffstat:
Atps/2C2024/1/scripts/input.txt | 1+
Atps/2C2024/1/scripts/publisher.py | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Atps/2C2024/1/scripts/subscriber.py | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 101 insertions(+), 0 deletions(-)
diff --git a/tps/2C2024/1/scripts/input.txt b/tps/2C2024/1/scripts/input.txt
@@ -0,0 +1 @@
+Hello, World!
diff --git a/tps/2C2024/1/scripts/publisher.py b/tps/2C2024/1/scripts/publisher.py
@@ -0,0 +1,49 @@
+import paho.mqtt.client as mqtt
+import random
+import time 
+# Configuración
+broker_address = "broker.hivemq.com"
+#broker_address = "mqtt-dashboard.com"
+
+topic = "tp1/kloeckner"
+min_size = 50  # Tamaño mínimo del fragmento
+max_size = 70  # Tamaño máximo del fragmento
+file_to_publish = 'input.txt'
+
+def on_connect(client, userdata, flags, rc):
+    # Al conectarse, configuramos la opción TCP_NODELAY
+    client_socket = client._socket().socket  # Accede al socket subyacente
+    client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)  # Desactiva Nagle
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+    print("Subscribed: "+str(mid)+" "+str(granted_qos))
+        
+def publish_file(client, filename, min_size, max_size):
+    with open(filename, 'r') as file:
+        content = file.read()
+
+    index = 0
+    fragment_number = 0
+    while index < len(content):
+        fragment_size = random.randint(min_size, max_size)
+        fragment = content[index:index+fragment_size]
+        
+        # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
+        is_last = 1 if index + fragment_size >= len(content) else 0
+        payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'        
+        client.publish(topic, payload, qos=2, retain=False)
+        print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
+        index += fragment_size
+        fragment_number += 1
+        time.sleep(1)
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_connect = on_connect  # Añade el manejador de eventos para cuando se conecte
+client.on_subscribe = on_subscribe # Añade el manejador de suscripción
+client.connect(broker_address, 1883, 60)
+
+# Publicar el archivo fragmentado
+publish_file(client, file_to_publish, min_size, max_size)
+
+client.disconnect()
diff --git a/tps/2C2024/1/scripts/subscriber.py b/tps/2C2024/1/scripts/subscriber.py
@@ -0,0 +1,50 @@
+import paho.mqtt.client as mqtt
+
+# Configuración
+broker = "broker.hivemq.com"
+#broker = "mqtt-dashboard.com"
+
+topic = "tp1/kloeckner"
+output_file = 'output.txt'
+received_fragments = {}
+last_fragment = False
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+    print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def on_message(client, userdata, msg):
+    global last_fragment
+    
+    
+    # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido
+    payload = msg.payload.decode('utf-8')
+    fragment_info, fragment = payload.rsplit('|', 1)
+    fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3])
+    
+    received_fragments[fragment_number] = (fragment_size, fragment)
+    print(f"Fragmento recibido {fragment_number} (size: {fragment_size})")    
+    if is_last == 1:
+        last_fragment = True
+    
+    # Reensamblar si es el último fragmento
+    if last_fragment:
+        reassemble_file(output_file)
+        quit()
+
+def reassemble_file(filename):
+    with open(filename, 'w') as file:
+        for fragment_number in sorted(received_fragments):
+            fragment_size, fragment = received_fragments[fragment_number]
+            file.write(fragment[:fragment_size])  # Reescribimos usando el largo correcto
+    print(f"File reassembled as {filename}")
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_message = on_message
+client.on_subscribe = on_subscribe
+
+client.connect(broker, 1883, 60)
+client.subscribe(topic, qos=2)
+
+# Mantener el cliente en funcionamiento
+client.loop_forever()
+\ No newline at end of file