From 37146b3081efc433b78b1f04411ba60de23300cf Mon Sep 17 00:00:00 2001 From: DJ2LS <75909252+DJ2LS@users.noreply.github.com> Date: Sat, 29 May 2021 15:48:27 +0200 Subject: [PATCH] socket timeout close the socket if timeout is reached --- sock.py | 22 ++++++++++++++++++---- static.py | 3 ++- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/sock.py b/sock.py index 17066946..68d304ca 100644 --- a/sock.py +++ b/sock.py @@ -21,22 +21,34 @@ import helpers class CMDTCPRequestHandler(socketserver.BaseRequestHandler): def handle(self): - while 1: + + # loop through socket buffer until timeout is reached. then close buffer + socketTimeout = time.time() + 3 + while socketTimeout > time.time(): time.sleep(0.01) encoding = 'utf-8' #data = str(self.request.recv(1024), 'utf-8') data = bytes() - while True: - chunk = self.request.recv(8192) # .strip() + + # we need to loop through buffer until end of chunk is reached or timeout occured + while True and socketTimeout > time.time(): + chunk = self.request.recv(1024) # .strip() data += chunk if chunk.endswith(b'\n'): break data = data[:-1] # remove b'\n' data = str(data, 'utf-8') + if len(data) > 0: + socketTimeout = time.time() + static.SOCKET_TIMEOUT + # convert data to json object - received_json = json.loads(data) + # we need to do some error handling in case of socket timeout + try: + received_json = json.loads(data) + except: + pass print(received_json) # GET COMMANDS @@ -216,6 +228,8 @@ class CMDTCPRequestHandler(socketserver.BaseRequestHandler): if received_json["type"] == 'SET' and received_json["command"] == 'DEL_RX_BUFFER': static.RX_BUFFER = [] + + print("sock timeout...") def start_cmd_socket(): diff --git a/static.py b/static.py index 77f142e4..2a2b91a1 100644 --- a/static.py +++ b/static.py @@ -19,8 +19,9 @@ DXGRID = b'' # --------------------------------- # Server Defaults -HOST = "localhost" +HOST = "0.0.0.0" PORT = 3000 +SOCKET_TIMEOUT = 3 # seconds # --------------------------------- # HAMLIB DEFAULTS