Send a file through sockets in Python

You must put all the code from sc, address = s.accept() upto sc.close() into another loop or the server simply terminates after receiving the first file. It doesn’t crash, the script is just finished.

[EDIT] Here is the revised code:

import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
s.listen(10) # Accepts up to 10 connections.

while True:
    sc, address = s.accept()

    print address
    i=1
    f = open('file_'+ str(i)+".pdf",'wb') #open in binary
    i=i+1
    while (True):       
    # receive data and write it to file
        l = sc.recv(1024)
        while (l):
                f.write(l)
                l = sc.recv(1024)
    f.close()


    sc.close()

s.close()

Note that s.listen(10) means “set maximum accept rate to 10 connections“, not “stop after 10 connections”.

Leave a Comment