在 Python 中通过套接字发送文件 [英] Send a file through sockets in Python
问题描述
我正在尝试用 python 编写一个实现套接字的程序.每个客户端发送一个 PDF 文件,服务器接收它并且将标题更改为file_(number).pdf".(例如:file_1.pdf).出现的问题是只有客户端才能成功发送文件.当第二个客户端尝试发送文件时,程序崩溃.我做错了什么,如何解决我的代码以允许 N 个客户端(N <20)连接到服务器并传输文件?
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?
这是服务器代码:
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()
这是客户端代码:
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()
为了简化我的代码,我总是使用文件名为libroR.pdf"的书,但在完整代码中,它是由 GUI 选择的.
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.
推荐答案
你必须把所有的代码从 sc, address = s.accept()
到 sc.close()
进入另一个循环,或者服务器在收到第一个文件后简单地终止.它没有崩溃,脚本刚刚完成.
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.
这是修改后的代码:
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()
请注意,s.listen(10)
的意思是将最大接受率设置为 10 个连接",而不是在 10 个连接后停止".
Note that s.listen(10)
means "set maximum accept rate to 10 connections", not "stop after 10 connections".
这篇关于在 Python 中通过套接字发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!