2

basically this code is a server for a project that I am doing the client sends over 600 photos which then I want to be stored in a folder called incoming. first error was me running into my pickle data being Truncated while being sent to my server to try rectify this. I added a chunking system where it splits the data up into smaller chunks to make sure there is a smaller change of data being lost. doing this in theory should work. but when it has finished chunking all my data the server just quits out of the 'handle_client' function but gives me no errors and in turn leaves my client hanging and unresponsive until I shut the server down

import pickle
import socket
import os
import threading

HEADER = 64
PORT = 5050
SERVER = 'Left this out for obvious reasons'
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "..DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")
    connected = True
    while connected:
        data_length = conn.recv(HEADER).decode(FORMAT)
        if data_length:
            data_length = int(data_length)
            recv_data = conn.recv(data_length)
            bytes_received = 0
            while bytes_received < data_length:
                chunk = conn.recv(4096)
                recv_data += chunk
                bytes_received += len(chunk)
            data = pickle.loads(recv_data)
            if data == DISCONNECT_MESSAGE:
                connected = False
            try:
                for files in os.listdir('incoming'):
                    file_path = os.path.join('incoming', files)
                    os.remove(file_path)
            except:
                print('[SERVER_ERROR] No files inside ./Incoming/ folder')

            for file in data:
                with open(os.path.join('incoming', file['name']), "wb") as f:
                    f.write(file['data'])
                    print('[SAVING] Server has saved file')
            


            with open('siamesemodel.h5','rb') as f:
                data = f.read()
                pickledData = pickle.dumps(data)
                data_length = len(pickledData)
                send_length = str(data_length).encode(FORMAT)
                send_length += b' ' * (HEADER - len(send_length))
                conn.send(send_length)
                conn.send(pickledData)

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.active_count() - 1}")


print("[STARTING] server is starting...")
start()

tried debugging to no avail

Harvey1G
  • 21
  • 2

0 Answers0