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 sockets = 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.")
Can you sand it to an other computer (live a virtual machine) ? thanks for the script :D
ReplyDeleteYou 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.
DeleteDoes this only work with LAN networks?
ReplyDeleteWith 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.
Deleteokay
Deletecan send file on private ip address
ReplyDelete