![](/img/trans.png)
[英]sending Image from Socket server (java) to socket client (python)
[英]Sending files to client from server via socket/ftp python
我是python的新手。 使用 Ubuntu 18.04,python 3.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'
無法弄清楚錯誤。
任何建議都會有所幫助。 感謝您。
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
可能只發送部分數據,您必須檢查返回值以了解發送了多少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.