File Transfer using TCP Socket in Python3

ADVERTISEMENT

In today’s tutorial, we are going to learn to do file transfer using a TCP socket in the python3 programming language. This is the most basic file transfer program that we can do using a client-server architecture. Here, we are going to do the build a client and a server program file, where the client read the data from a text file and send it to the server. The server receives it and saves the data to another text file.

The overall procedure for the TCP file transfer is presented in the figure below.

TCP file transfer using a client-server program.

Related Tutorials

More Interested in File Transfer using the C programming language? Check out the tutorial below to learn more.

What is TCP?

TCP stands for Transmission Control Protocol. It is a communication protocol that is designed for end-to-end data transmission over a network. TCP is basically the ” standard” communication protocol for data transmission over the Internet.

It is a highly efficient and reliable communication protocol as it uses a three-way handshake to connect the client and the server. It is a process that requires both the client and the server to exchange synchronization (SYN) and acknowledge (ACK) packets before the data transfer takes place.

Some of the features of the TCP are as follows:

  1. It provides end-to-end communication.
  2. It is a connection-oriented protocol.
  3. It provides error-checking and recovery mechanisms.

Project Structure

The project is divided into two files:

  1. server.py
  2. client.py

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.

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 from the client and create a text file.
  6. Send a response back to the client.
  7. Receive the text data from the client.
  8. Write (save) the data into the text file.
  9. Send a response message back to the client.
  10. Close the text file.
  11. Close the connection.
import socket

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

def main():
    print("[STARTING] Server is starting.")
    """ Staring a TCP socket. """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    """ Bind the IP and PORT to the server. """
    server.bind(ADDR)

    """ Server is listening, i.e., server is now waiting for the client to connected. """
    server.listen()
    print("[LISTENING] Server is listening.")

    while True:
        """ Server has accepted the connection from the client. """
        conn, addr = server.accept()
        print(f"[NEW CONNECTION] {addr} connected.")

        """ Receiving the filename from the client. """
        filename = conn.recv(SIZE).decode(FORMAT)
        print(f"[RECV] Receiving the filename.")
        file = open(filename, "w")
        conn.send("Filename received.".encode(FORMAT))

        """ Receiving the file data from the client. """
        data = conn.recv(SIZE).decode(FORMAT)
        print(f"[RECV] Receiving the file data.")
        file.write(data)
        conn.send("File data received".encode(FORMAT))

        """ Closing the file. """
        file.close()

        """ Closing the connection from the client. """
        conn.close()
        print(f"[DISCONNECTED] {addr} disconnected.")

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. Read the data from the text file.
  4. Send the filename to the server.
  5. Receive the response from the server.
  6. Send the text file data to the server.
  7. Receive the response from the server.
  8. Close the file.
  9. Close the connection.
import socket

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

def main():
    """ Staring a TCP socket. """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    """ Connecting to the server. """
    client.connect(ADDR)

    """ Opening and reading the file data. """
    file = open("data/yt.txt", "r")
    data = file.read()

    """ Sending the filename to the server. """
    client.send("yt.txt".encode(FORMAT))
    msg = client.recv(SIZE).decode(FORMAT)
    print(f"[SERVER]: {msg}")

    """ Sending the file data to the server. """
    client.send(data.encode(FORMAT))
    msg = client.recv(SIZE).decode(FORMAT)
    print(f"[SERVER]: {msg}")

    """ Closing the file. """
    file.close()

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


if __name__ == "__main__":
    main()

Summary

In this article, you have learned a simple file transfer using TCP 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

ADVERTISEMENT

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

Related Posts

Leave a Reply

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