0

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!!!

1 Answers1

0

You can have a lot of improvement in your code.

First, make the server where you want to receive the file so that you can keep it running and bind the port only there and not on the client-side. Also, you are using while loop is wrong as you will never get out of it.

Server 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')
data, addr = sock.recvfrom(1024)

while data:
    print(data)
    if data.decode("utf-8")=="Now":
        break
    f.write(data)
    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!')

Client 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)

f = open(file_name, "r")
data = f.read(buffer_size)

while data:
    print(data)
    if(sock.sendto(str.encode(data), (host, port))):
        data = f.read(buffer_size)
sock.sendto(str.encode("Now"),(host, port))
sock.close()
f.close()

Note: I am sending Now just for letting the server know that the file is finished, you can send anything else.

HARSH MITTAL
  • 750
  • 4
  • 17