Large File Transfer using TCP Socket in Python

File transfer has been one of many tasks in socket programming. In this article, we will discuss how to transfer large files using TCP sockets in Python. TCP (Transmission Control Protocol) is a reliable and efficient data transmission protocol commonly used for file transfers over the internet. With Python’s in-built socket library, it is easy to implement a TCP socket for file transfer purposes. This article will provide a step-by-step guide on how to create a TCP server and client in Python and how to send large files using this protocol. Whether you are a beginner or an experienced Python programmer, this article is designed to help you understand how to implement this solution. So, let’s dive into the world of TCP sockets and large file transfers in Python!

What is TCP?

TCP stands for Transmission Control Protocol. It is a type of computer networking protocol that is used to send data between computers in a network. The main job of TCP is to ensure that data is transmitted accurately and efficiently from one computer to another, regardless of any network issues that might arise.

TCP is a protocol that helps computers send data to each other in a reliable and efficient way.

Imagine you are sending a letter to someone through the postal service. The postal service is like the internet and the letter is like the data you are trying to send. Just like you want to make sure your letter reaches its destination safely and without any errors, the TCP protocol ensures that the data you send over the internet reaches its destination accurately and without any errors.

Related Tutorials

Project Structure

The project is divided into two files:

  1. server.py
  2. client.py
  3. friends-final.txt

The client.py contains the code, used to read a text file and send its data to the server. While the server.py file receives the data sent by the client and save it to a text file.

The friends-final.txt is the text file containing the textual data which needs to be transferred.

File Transfer: SERVER

The server performs the following functions:

  1. Create a TCP socket.
  2. Bind the IP address and PORT to the server socket.
  3. Listening for the clients.
  4. Accept the connection from the client.
  5. Receive the filename and its total size from the client.
  6. Send a response (Filename and filesize received from the client) back to the client.
  7. Create a text file.
  8. Start receiving a fix-size text data from the client.
  9. Write (save) the data into the text file.
  10. Send a response message back to the client.
  11. Repeat the step 8,9 and 10. Until the client send a blank data message. This means that the data transfer is completed.
  12. Close the text file.
  13. Close the connection.
import socket
from tqdm import tqdm

IP = socket.gethostbyname(socket.gethostname())
PORT = 4456
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"

def main():
    """ Creating a TCP server socket """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(ADDR)
    server.listen()
    print("[+] Listening...")

    """ Accepting the connection from the client. """
    conn, addr = server.accept()
    print(f"[+] Client connected from {addr[0]}:{addr[1]}")

    """ Receiving the filename and filesize from the client. """
    data = conn.recv(SIZE).decode(FORMAT)
    item = data.split("_")
    FILENAME = item[0]
    FILESIZE = int(item[1])

    print("[+] Filename and filesize received from the client.")
    conn.send("Filename and filesize received".encode(FORMAT))

    """ Data transfer """
    bar = tqdm(range(FILESIZE), f"Receiving {FILENAME}", unit="B", unit_scale=True, unit_divisor=SIZE)

    with open(f"recv_{FILENAME}", "w") as f:
        while True:
            data = conn.recv(SIZE).decode(FORMAT)

            if not data:
                break

            f.write(data)
            conn.send("Data received.".encode(FORMAT))

            bar.update(len(data))

    """ Closing connection. """
    conn.close()
    server.close()

if __name__ == "__main__":
    main()

File Transfer: CLIENT

The client performs the following functions:

  1. Create a TCP socket for the client.
  2. Connect to the server.
  3. Send the filename and total file size to the server.
  4. Receive the response (Filename and filesize received) from the server.
  5. Open the text file and start reading it.
  6. Send a fix-size text data to the server.
  7. Receive the response from the server.
  8. Repeat the 6 and 7. Until no data is left to be transferred.
  9. Close the file.
  10. Close the connection.
import os
import socket
from tqdm import tqdm

IP = socket.gethostbyname(socket.gethostname())
PORT = 4456
ADDR = (IP, PORT)
SIZE = 1024
FORMAT = "utf-8"
FILENAME = "friends-final.txt"
FILESIZE = os.path.getsize(FILENAME)

def main():
    """ TCP socket and connecting to the server """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(ADDR)

    """ Sending the filename and filesize to the server. """
    data = f"{FILENAME}_{FILESIZE}"
    client.send(data.encode(FORMAT))
    msg = client.recv(SIZE).decode(FORMAT)
    print(f"SERVER: {msg}")

    """ Data transfer. """
    bar = tqdm(range(FILESIZE), f"Sending {FILENAME}", unit="B", unit_scale=True, unit_divisor=SIZE)

    with open(FILENAME, "r") as f:
        while True:
            data = f.read(SIZE)

            if not data:
                break

            client.send(data.encode(FORMAT))
            msg = client.recv(SIZE).decode(FORMAT)

            bar.update(len(data))

    """ Closing the connection """
    client.close()

if __name__ == "__main__":
    main()

Output

 The output of the program on the Terminal.
The output of the program on the Terminal.

Summary

In this article, you have learned how to transfer a large text file in small chunks over TCP client-server connection in the python 3 programming language. Still, have some questions or queries? Just comment below. For more updates. Follow me.

Read More

  1. How to Transfer Files in the Network using Sockets in Python
  2. Python Socket File Transfer Send

Nikhil Tomar

I am an independent researcher in the field of Artificial Intelligence. I love to write about the technology I am working on.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *