我已经制作了这个发送/接收脚本,但我损坏了文件!我不知道为什么我会遇到这个问题!
发件人.py
#!/usr/bin/env python
from socket import *
import sys
s = socket(AF_INET,SOCK_DGRAM)
host =sys.argv[1]
port = 9999
buf =1024
addr = (host,port)
file_name=sys.argv[2]
f=open(file_name,"rb")
data = f.read(buf)
s.sendto(file_name,addr)
s.sendto(data,addr)
while (data):
if(s.sendto(data,addr)):
print "sending ..."
data = f.read(buf)
s.close()
f.close()
接收器.py
#!/usr/bin/env python
from socket import *
import sys
import select
host="0.0.0.0"
port = 9999
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=1024
data,addr = s.recvfrom(buf)
print "Received File:",data.strip()
f = open(data.strip(),'wb')
data,addr = s.recvfrom(buf)
try:
while(data):
f.write(data)
s.settimeout(2)
data,addr = s.recvfrom(buf)
except timeout:
f.close()
s.close()
print "File Downloaded"
这是我修改过的原始接收器(工作正常 100%)
#!/usr/bin/env python
from socket import *
import sys
import select
host="0.0.0.0"
port = 9999
s = socket(AF_INET,SOCK_DGRAM)
s.bind((host,port))
addr = (host,port)
buf=1024
f = open("file.pdf",'wb')
data,addr = s.recvfrom(buf)
try:
while(data):
f.write(data)
s.settimeout(2)
data,addr = s.recvfrom(buf)
except timeout:
f.close()
s.close()
print "File Donwloaded"
正如您所注意到的,它在开始时正在制作文件。
严格:客户端=>发送文件(name.ext)=>服务器:保存它(name.ext)
我的输出:pdf文件损坏,txt文件为空