forked from prathimacode-hub/Awesome_Python_Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_transfer_server.py
49 lines (42 loc) · 1.92 KB
/
file_transfer_server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import socket
def create_socket():
try:
global host
global port
global s
host = ""
port = 2110 # port no through which communication will take place
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # creating a socket
except socket.error as msg:
print("Socket Creation Error:" + str(msg)) # error message in case a socket can't be created
def bind_socket():
try:
global host
global port
global s
print("Binding with port:" + str(port))
s.bind((host, port)) # to bind with the port
s.listen(5) # to listen to the client for information
except socket.error as msg: # error in case the socket could not be binded
print("Socket Binding error:" + str(msg))
print("Retrying.........")
bind_socket()
def socket_accept():
while True:
clt_soc, add = s.accept() # to accept the client socket and address
# print the I/P and port no through which communication has been established
print("Connection has been established:IP......." + add[0] + " and Port:" + str(add[-1]))
receive_file(clt_soc) # function to receive the file
clt_soc.close() # to close the socket after communication
def receive_file(clt_soc):
filename = clt_soc.recv(1024).decode("utf-8") # to receive file name and decode it
file = open(filename, "w") # to open a file with the received filename in write mode
print(filename) # to print the file name
data = clt_soc.recv(1024).decode("utf-8") # to receive the data of the file
file.write(data) # to write the contents of the file in the new file
clt_soc.send("File received.".encode("utf-8")) # to send that file has been received
file.close() # to close the file
if __name__ == '__main__':
create_socket()
bind_socket()
socket_accept()