Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

Send a file through sockets in Python

I'm trying to make a program in python that implements sockets. Each client sends a PDF file and the server receives it and the title is changed to "file_(number).pdf" (e.g.: file_1.pdf). The problem presented is that only a client can send a file successfully. When a second client tries to send the file, the program crashes. What am I doing wrong and how can I solve my code to allow N clients (with N < 20) to connect to the server and transfer files?

Here's the server code:

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

print address
i=1
f = open('file_'+ str(i)+".pdf",'wb') # Open in binary
i=i+1
while (True):

    # We receive and write to the file.
    l = sc.recv(1024)
    while (l):
        f.write(l)
        l = sc.recv(1024)
f.close()

sc.close()
s.close()

Here's the client code:

import socket
import sys

s = socket.socket()
s.connect(("localhost",9999))
f = open ("libroR.pdf", "rb")
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
s.close()

To simplify my code, I always use a book with file name "libroR.pdf", but in the full code it is chosen by a GUI.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...