How to Transfer Files in the Network using Sockets in Python

Published on Aug. 22, 2023, 12:15 p.m.

To transfer files over a network using sockets in Python, you can use the socket library along with some additional modules like os and tqdm. Here is a sample code that shows how to send a file from a server to a client over a network:

Server code:

import socket
import os
from tqdm import tqdm

# define the host and port
HOST = '0.0.0.0'
PORT = 5555

# create a socket object and bind it to the host and port
s = socket.socket()
s.bind((HOST, PORT))

# listen for incoming connections
s.listen(5)
print(f"Server is listening on {HOST}:{PORT}")

# accept the connection
client_socket, address = s.accept()
print(f"Connection from {address} has been established!")

# send the file size to the client
filesize = os.path.getsize('myfile.txt')
client_socket.send(f"{filesize}".encode())

# send the file data to the client
with open('myfile.txt', 'rb') as f:
    progress = tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
    for _ in progress:
        # read the bytes from the file
        bytes_read = f.read(1024)
        if not bytes_read:
            # if file has been read completely, break
            break

        # send the bytes to the client
        client_socket.sendall(bytes_read)
        # update the progress bar
        progress.update(len(bytes_read))

# close the connection
client_socket.close()
s.close()

Client code:

import socket
import os
from tqdm import tqdm

# define the host and port
HOST = '192.168.1.101'
PORT = 5555

# create a socket object and connect to the server
s = socket.socket()
s.connect((HOST, PORT))

# receive the file size from the server
filesize = int(s.recv(1024).decode())

# receive the file data from the server
with open('received_file.txt', 'wb') as f:
    progress = tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
    for _ in progress:
        # receive the bytes from the server
        bytes_read = s.recv(1024)
        if not bytes_read:    
            # if all bytes have been received, break
            break

Tags: