通过socket/ftp python从服务器向客户端发送文件

2024-03-28 14:28:07 发布

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

我对Python还不熟悉。使用ubuntu18.04,python3.6。你知道吗

尝试编写脚本将任何文件从服务器发送到客户端(当前尝试发送.pdf文件),反之亦然。你知道吗

早些时候,我使用套接字发送文件,但遇到了扩展名问题(比如发送.pdf文件,但收到.txt文件-无法找出发生这种情况的原因)。然后使用ftp,但现在卡在一个点上。你知道吗

服务器脚本:

import socket
import os

s = socket.socket()
host = ""
port = 9999

s.bind((host, port))
s.listen(5)
print("Binding Done\n")

socket_object, address = s.accept()
print("Connection Established\n")

print("Sending file...")
f = open("cds.pdf", 'rb')
while f.read(1024):
    socket_object.send(f.read(1024))

print("Files Send")
f.close()
socket_object.close()
s.close()

客户端脚本:

import socket
import os
from ftplib import FTP

ftp = FTP()
s = socket.socket()
host = "192.168.43.16"
port = 9999

s.connect((host, port))
#ftp.connect(host = "192.168.43.16", port = 9999)

print("Receiving data...")

f = open("cds_copy.pdf", 'wb')
while True:
    ftp.retrbinary('RETR cds_copy.pdf', f.write, 1024)

ftp.storbinary('STOR cds_copy.pdf', open('cds_copy.pdf', 'rb'))
print("File Collected")
ftp.quit()
f.close()
s.close()

错误:

$python3 client.py
Receiving data...
Traceback (most recent call last):
  File "client.py", line 17, in <module>
    ftp.retrbinary('RETR cds_copy.pdf', f.write, 1024)
  File "/usr/lib/python3.6/ftplib.py", line 441, in retrbinary
    self.voidcmd('TYPE I')
  File "/usr/lib/python3.6/ftplib.py", line 277, in voidcmd
    self.putcmd(cmd)
  File "/usr/lib/python3.6/ftplib.py", line 199, in putcmd
    self.putline(line)
  File "/usr/lib/python3.6/ftplib.py", line 194, in putline
    self.sock.sendall(line.encode(self.encoding))
AttributeError: 'NoneType' object has no attribute 'sendall'

无法找出错误。你知道吗

任何建议都会有帮助。谢谢你。你知道吗


Tags: 文件pyimporthostclosepdfportline
1条回答
网友
1楼 · 发布于 2024-03-28 14:28:07

FTP是RFC 959中定义的应用程序协议。如果你想在你的客户机中使用它,你必须有一个说FTP协议的服务器。服务器不使用FTP协议,只是将文件内容转储到客户端。在这种情况下,客户机应该期望这一点,而不是说FTP,即

import socket 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.43.16", 9999))
f = open("out.pdf","wb")
while True:
    buf = s.recv(1024)
    if buf == "":
        break
    f.write(buf)

除此之外,您的服务器已损坏:它首先从文件中读取1024字节,丢弃它,然后读取下一个1024字节并将其发送到客户端:

while f.read(1024):                           # read 1024 byte from f but discard
    socket_object.send(f.read(1024))          # read another 1024 byte from f and send

这可能不是你想要的。相反,它应该更像这样:

while True:
    buf = f.read(1024)              # read bytes from f
    if buf == "":                   # check that not done
        break
    socket_object.sendall(buf)     # write previously read bytes to client

注意,这也使用sendall而不是send,因为只有sendall会注意实际发送所有给定的数据。相反,一个简单的send可能只发送部分数据,您必须检查返回值以确定发送了多少数据。你知道吗

相关问题 更多 >