From 6c6f5dc1f56346adeb48cc669b13c49b508fbd9d Mon Sep 17 00:00:00 2001 From: =?utf8?q?Rapha=C3=ABl=20Couturier?= Date: Mon, 12 Jul 2021 11:43:19 +0200 Subject: [PATCH] new --- measure_energy_iot/client_tcp4.py | 32 +++++++++++++++++++ measure_energy_iot/server_tcp4.py | 52 +++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 measure_energy_iot/client_tcp4.py create mode 100644 measure_energy_iot/server_tcp4.py diff --git a/measure_energy_iot/client_tcp4.py b/measure_energy_iot/client_tcp4.py new file mode 100644 index 0000000..b96dbd3 --- /dev/null +++ b/measure_energy_iot/client_tcp4.py @@ -0,0 +1,32 @@ +import socket +import threading +import os + +import buffer + +HOST = 'bilbo' +PORT = 2345 + +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +s.connect((HOST, PORT)) + +with s: + sbuf = buffer.Buffer(s) + + +# files = input('Enter file(s) to send: ') + # files_to_send = files.split() + file_name="lena.jpg" + for i in range(10): +# for file_name in files_to_send: + print(file_name) + sbuf.put_utf8(file_name) + + file_size = os.path.getsize(file_name) + sbuf.put_utf8(str(file_size)) + + with open(file_name, 'rb') as f: + sbuf.put_bytes(f.read()) + print('File Sent') + + diff --git a/measure_energy_iot/server_tcp4.py b/measure_energy_iot/server_tcp4.py new file mode 100644 index 0000000..52c3afd --- /dev/null +++ b/measure_energy_iot/server_tcp4.py @@ -0,0 +1,52 @@ +import socket +import os + +import buffer + +HOST = 'bilbo' +PORT = 2345 + +# If server and client run in same local directory, +# need a separate place to store the uploads. +try: + os.mkdir('uploads') +except FileExistsError: + pass + +s = socket.socket() +s.bind((HOST, PORT)) +s.listen(10) +print("Waiting for a connection.....") + +while True: + conn, addr = s.accept() + print("Got a connection from ", addr) + connbuf = buffer.Buffer(conn) + + while True: + + + file_name = connbuf.get_utf8() + if not file_name: + break +# file_name = os.path.join('uploads',file_name) +# print('file name: ', file_name) + + file_size = int(connbuf.get_utf8()) + print('file size: ', file_size ) + + with open("/tmp/"+file_name, 'wb') as f: + remaining = file_size + while remaining: + chunk_size = 4096 if remaining >= 4096 else remaining + chunk = connbuf.get_bytes(chunk_size) + if not chunk: break + f.write(chunk) + remaining -= len(chunk) + if remaining: + print('File incomplete. Missing',remaining,'bytes.') + else: + print('File received successfully.') + print('Connection closed.') + conn.close() + -- 2.39.5