How to create a file transfer program using python 3.0 or above.




Based on the previous tutorial of how to create a chat program using python. This tutorial will be very similar and will use somewhat the same logic and flow of code.

Flow of code

Server : The server will host the network using the assigned host and port using which the client will connect to the server. The server will act as the sender and the user will have to input the filename of the file that he/she would like to transmit. The user must make sure that the file that needs to be sent is in the same directory as the "server.py" program.

Client: The client program will prompt the user to enter the host address of the server while the port will already be assigned to the port variable. Once the client program has connected to the server it will ask the user for a filename to be used for the file that will be received from the server. Lastly the client program will receive the file and leave it in the same directory under the same filename set as the user.

Server Side Code

import socket

s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host,port))
s.listen(1)
print(host)
print("Waiting for any incoming connections ... ")
conn, addr = s.accept()
print(addr, "Has connected to the server")

filename = input(str("Please enter the filename of the file : "))
file = open(filename , 'rb')
file_data = file.read(1024)
conn.send(file_data)
print("Data has been transmitted successfully")

Client Side Code

import socket
s = socket.socket()
host = input(str("Please enter the host address of the sender : "))
port = 8080
s.connect((host,port))
print("Connected ... ")

filename = input(str("Please enter a filename for the incoming file : "))
file = open(filename, 'wb')
file_data = s.recv(1024)
file.write(file_data)
file.close()
print("File has been received successfully.")

For better explanations and video tutorial please follow this link : https://www.youtube.com/watch?v=27qfn3Gco00


Comments

  1. Can you sand it to an other computer (live a virtual machine) ? thanks for the script :D

    ReplyDelete
    Replies
    1. You can send it to another computer. Simply port forward the port that is being used by the server and then use the same port on the client. It should work just fine.

      Delete
  2. Does this only work with LAN networks?

    ReplyDelete
    Replies
    1. With the code above, it will only work on LAN networks, you can make it work with other networks, by port forwarding the "port" being used by the server.

      Delete
  3. can send file on private ip address

    ReplyDelete

Post a Comment

Popular posts from this blog

How to create a chat program using python 3.0 or above