如何在这个Python套接字中调用文件名?

2024-10-04 03:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个基于Python套接字的文件传输脚本。服务器可以有10个客户机连接到它,所有的发送文件。问题是,它只发送一个名为'libroR.pdf文件,如果可能,我希望用户能够指定要发送到服务器的自定义文件的名称和位置。如果可能的话,我还希望能够为客户机指定一个自定义主机名以进行连接。在

服务器:

import socket
import sys

s = socket.socket()
s.bind(("localhost",9999))
s.listen(10) # Acepta hasta 10 conexiones entrantes.

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):       
    # recibimos y escribimos en el fichero
        l = sc.recv(1024)
        while (l):
                f.write(l)
                l = sc.recv(1024)
    f.close()


    sc.close()

s.close()

客户:

^{pr2}$

谢谢,肖恩。:)


Tags: 文件import服务器脚本trueclose客户机pdf
1条回答
网友
1楼 · 发布于 2024-10-04 03:20:34

试试这个:

import socket
import sys
s = socket.socket()
s.connect((raw_input("Enter a host name"),9999))
f = open(raw_input("Enter the file to send to the server: "), "rb") # On this line, you were getting a file allways named libroR.pdf, but the user can input the file now
l = f.read(1024)
while (l):
    s.send(l)
    l = f.read(1024)
s.close()

相关问题 更多 >