Skip to content

Commit 92c353c

Browse files
Create FileTransferScript.py
1 parent 1a9f213 commit 92c353c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

FileTransferScript.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import socket
2+
3+
# create socket
4+
s = socket.socket()
5+
6+
# bind socket to a address and port
7+
s.bind(('localhost', 12345))
8+
9+
# put the socket into listening mode
10+
s.listen(5)
11+
12+
print('Server listening...')
13+
14+
# forever loop to keep server running
15+
while True:
16+
# establish connection with client
17+
client, addr = s.accept()
18+
print(f'Got connection from {addr}')
19+
20+
# receive the file name
21+
file_name = client.recv(1024).decode()
22+
23+
try:
24+
# open the file for reading in binary
25+
with open(file_name, 'rb') as file:
26+
# read the file in chunks
27+
while True:
28+
chunk = file.read(1024)
29+
if not chunk:
30+
break
31+
# send the chunk to the client
32+
client.sendall(chunk)
33+
34+
print(f'File {file_name} sent successfully')
35+
except FileNotFoundError:
36+
# if file not found, send appropriate message
37+
client.sendall(b'File not found')
38+
print(f'File {file_name} not found')
39+
40+
# close the client connection
41+
client.close()

0 commit comments

Comments
 (0)