【问题标题】:How to call file name in this Python Socket?如何在这个 Python Socket 中调用文件名?
【发布时间】:2012-10-02 16:48:57
【问题描述】:

我正在开发基于 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()

客户:

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()

谢谢,肖恩。 :)

【问题讨论】:

  • 你能修复缩进吗?看起来你的 while 循环变平了。
  • 是的,我明白了。刚刚修好了。

标签: python sockets network-programming


【解决方案1】:

试试这个:

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()

【讨论】:

  • 我认为您误读了代码。客户端没有尝试从套接字接收。它正在读取文件并将其发送到套接字。
  • 我知道。当您发送此评论时,我正在更改它。对不起。
  • @Tommy3244,我喜欢 :) 这么看来,这是否意味着服务器也必须稍作修改? :3
  • 另外,我刚刚测试过了。它完美地传输文件,但它会生成一个名为“file_1.pdf”的空文件,然后如果您传输 PDF 文件,则等待向其发送某些内容并将数据写入该文件。想知道如何将其保存为与输入服务器相同的名称和扩展名......有什么想法吗?谢谢:)
猜你喜欢
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多