I coded a simple TCP server – client file sharing but it only work when the script close the socket in the client side.
I tried to remove the s.close inside the client python script and it gave me an error. Any idea?
I dont know if it even possible to do this kind of things with TCP without closing socket.
here is my code
server.py
import socket
import tqdm
import os
SERVER_HOST = "192.168.1.48"
SERVER_PORT = 5001
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
s = socket.socket()
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
client_socket, address = s.accept()
print(f"[+] {address} is connected.")
def receive_file(filename):
received = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
while True:
# read 1024 bytes from the socket (receive)
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
# nothing is received
# file transmitting is done
break
# write to the file the bytes we just received
f.write(bytes_read)
# update the progress bar
progress.update(len(bytes_read))
while True:
command = input("-->")
client_socket.send(str.encode(command))
filename = command[9:]
receive_file(filename)
client.py
import socket
import tqdm
import os
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096 # send 4096 bytes each time step
host = "192.168.1.48"
port = 5001
filesize = os.path.getsize(filename)
s = socket.socket()
print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")
def send_file(filename,filesize):
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
# file transmitting is done
break
s.sendall(bytes_read)
progress.update(len(bytes_read))
# close the socket
s.close()
while True:
command = s.recv(4096)
if command[:8].decode("utf-8") == "download":
print("yes it start")
filename = command[9:].decode("utf-8")
print(filename)
filesize = os.path.getsize(filename)
send_file(filename,filesize)
>Solution :
Break out of the loop when you’ve received filesize bytes.
with open(filename, "wb") as f:
total_bytes = 0
while total_bytes < filesize:
# read 1024 bytes from the socket (receive)
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
# nothing is received
# file transmitting is done
break
# write to the file the bytes we just received
f.write(bytes_read)
total_bytes += len(bytes_read)
# update the progress bar
progress.update(len(bytes_read))