To write a python program for creating File Transfer using TCP Sockets Links
- Import the necessary python modules.
- Create a socket connection using socket module.
- Send the message to write into the file to the client file.
- Open the file and then send it to the client in byte format.
- In the client side receive the file from server and then write the content into it.
import socket
s = socket.socket()
host = socket.gethostname()
port = 60000
s.connect((host, port))
s.send("Hello server!".encode())
with open('received_file', 'wb') as f:
print('receiving data...')
while True:
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
f.write(data)
print('Successfully received the file')
s.close()
print('connection closed')
import socket
port = 60000
s = socket.socket()
host = socket.gethostname()
s.bind((host, port))
s.listen(5)
print("Server listening on port", port)
while True:
conn, addr = s.accept()
print("Connected to", addr)
data = conn.recv(1024)
print('Server received', repr(data))
filename = 'C:\\Users\\SEC\\Desktop\\Prabha.txt'
with open(filename, 'rb') as f:
l = f.read(1024)
while l:
conn.send(l)
print('Sent', repr(l))
l = f.read(1024)
print('Done sending')
conn.send('Thank you for connecting'.encode())
conn.close()
Thus, the python program for creating File Transfer using TCP Sockets Links was successfully created and executed.