FILE TRANSFER BETWEEN CLIENT SIDE AND SIDE
Introduction:
A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.
CODE :
# server.py
import socket
def start_server(host='0.0.0.0', port=5001, buffer_size=4096, save_file='received_file.txt'):
# Create a socket and bind it to the specified host and port
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(5)
print(f"Server listening on {host}:{port}")
# Wait for a client connection
conn, addr = server_socket.accept()
print(f"Connection from {addr} established.")
# Open file to write the incoming data
with open(save_file, 'wb') as f:
while True:
# Read data from the client in chunks
bytes_read = conn.recv(buffer_size)
if not bytes_read:
break # No more data, file received
f.write(bytes_read)
print(f"File received and saved as '{save_file}'")
# Close the connection and the socket
conn.close()
server_socket.close()
print("Server connection closed.")
if name == "main":
start_server()
# client.py
import socket
import os
def send_file(file_path, host='127.0.0.1', port=5001, buffer_size=4096):
# Verify if the file exists
if not os.path.exists(file_path):
print(f"File '{file_path}' does not exist.")
return
# Create a socket and connect to the server
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
print(f"Connected to server at {host}:{port}")
# Open the file and send it in chunks
with open(file_path, 'rb') as f:
while True:
# Read file data in chunks
bytes_read = f.read(buffer_size)
if not bytes_read:
break # End of file
client_socket.sendall(bytes_read)
print(f"File '{file_path}' sent successfully.")
# Close the socket
client_socket.close()
print("Client connection closed.")
if name == "main":
file_to_send = "file_to_send.txt" # Specify the file to send
send_file(file_to_send)
No comments:
Post a Comment