I have started to learn socket programming recently. I am trying to write a python program to transfer a file to client from server. I have written the following code. It's running just fine...but I am not getting the file in the client side(may be transfer is not happening).
This the the server side code:
import socket
host = "127.0.0.1"
port = 12000
buffer_size = 1024
file_name = 'Myfile.txt'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host,port))
sock.sendto(file_name.encode(),(host,port))
f = open(file_name, "r")
data = f.read(buffer_size)
while data:
print(data)
if(sock.sendto(data.encode(), (host, port))):
data = f.read(buffer_size)
sock.close()
f.close()
This is the client side code:
import socket
host = "127.0.0.1"
port = 12000
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host,port))
f= open('Myfile2.txt','wb')
print('New file created')
while True:
data, addr = sock.recvfrom(1024)
print(data)
while(data):
f.write(data.decode("utf-8"))
data, addr = sock.recvfrom(1024)
print('File is successfully received!!!')
f.close()
f = open('Myfile2.txt','r')
print(f.read)
f.close()
sock.close()
print('Connection closed!')
Can anyone help me to find the problem in my code? Thanks in advance!!!