File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments