Python | File Download Case

File download case


TCP server side:

import socket, os

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind(('192.168.31.199', 9090))
server_socket.listen(128)

# Receive client request
client_socket, client_addr = server_socket.accept()
file_name = client_socket.recv(1024).decode('utf8')

# print('Received data from {}address{}port, the content is:{}'.format(client_addr[0], client_addr[1], data))
if os.path.isfile(file_name):
# print('Read the file and return it to the client')
with open(file_name, 'rb') as file:
content = file.read()
client_socket.send(content)
else:
print('The file does not exist')
TCP client:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(('192.168.31.199', 9090))

# s.send('hello'.encode('utf8'))
file_name = input('Enter the name of the file you want to download:')
s.send(file_name.encode('utf8'))

with open(file_name, 'wb') as file:
while True:
content = s.recv(1024)
if not content:
break
file.write(content)

s.close()

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone Contact Us