File Transfer using TCP Socket in Python

File Transfer using TCP Socket in Python

Transferring files using TCP sockets in Python involves creating a server that listens for incoming connections and a client that connects to the server to send the file. Below is a basic example demonstrating how to implement a file transfer system using Python's built-in socket module.

Server (Receiver)

The server listens for connections and once a client connects, it receives the file sent by the client.

import socket def receive_file(filename, server_ip, server_port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((server_ip, server_port)) s.listen() print("Server listening...") conn, addr = s.accept() with conn: print(f"Connected by {addr}") with open(filename, 'wb') as f: while True: data = conn.recv(1024) if not data: break f.write(data) print("File received successfully.") # Usage receive_file("received_file.txt", "127.0.0.1", 65432) 

Client (Sender)

The client connects to the server and sends the file.

import socket def send_file(filename, server_ip, server_port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((server_ip, server_port)) with open(filename, 'rb') as f: while True: data = f.read(1024) if not data: break s.sendall(data) print("File sent successfully.") # Usage send_file("path_to_your_file.txt", "127.0.0.1", 65432) 

Running the Example

  1. Server: Run the server script on one machine or in one terminal window. It will start listening for incoming connections.

  2. Client: Run the client script on another machine or in another terminal window, specifying the file you want to send and the server's IP address and port.

Important Notes

  • Make sure the server is running and listening before starting the client.
  • The server and client must be reachable over the network. If testing on a single machine, use localhost or 127.0.0.1 as the IP address.
  • This is a basic example. In a production environment, you should handle exceptions, ensure secure connections, and potentially implement authentication.
  • The size of recv buffer (here, 1024 bytes) can be adjusted based on your network and file size. Larger files may benefit from a larger buffer, but keep in mind the limitations of your network and system.
  • The server in this example handles one connection and then closes. For handling multiple clients, you can implement threading or use asynchronous IO.

More Tags

create-react-app woocommerce whatsapp tidyselect vuejs2 xcode11 higher-order-components sidebar exception phpexcel

More Programming Guides

Other Guides

More Programming Examples