在python中发送/接收文件UDP [英] sending/receiving file UDP in python
问题描述
我已经制作了这个发送/接收脚本,但是我损坏了文件! 我不知道为什么会遇到这个问题!
I've made this sending / receiving scripts but i corrupted file ! i have no idea why I'm getting this issue !
sender.py
sender.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()
receiver.py
receiver.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%正常工作)
and this the original receiver that I've modify it (works fine 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"
正如您所注意到的,它在一开始就是文件.
as you notice it's making file at the beginning.
已实现: 客户端=>发送文件(name.ext)=>服务器:保存文件(name.ext)
exacted: client => send file (name.ext) => server:save it (name.ext)
我的输出: pdf损坏的文件,txt损坏的空文件
my output : corrupted file for pdf and empty for txt
推荐答案
这里有两个问题:
您正在使用from socket import *
.它本身不是一个错误,但是当您执行except socket.timeout
时它会变成一个错误.
You're using a from socket import *
. It's not an error on its own, but it becomes one when you do except socket.timeout
.
使用UDP,腐败不会令人惊讶.您可能不想在这里使用UDP,应该切换到TCP.
Using UDP, corruption shouldn't be a surprise. You probably don't want to be using UDP here, you should switch to TCP.
这就是为什么UDP在这里不合适的原因:
Here's why UDP is not appropriate here:
- 数据包可能会丢失,但其他数据包仍可以到达目的地.
- 数据包可能重复
- 数据包可能以错误的顺序到达
请注意,切换到TCP会涉及一些代码重构(将SOCK_DGRAM
替换为SOCK_STREAM
有点复杂),但是对于您而言,您必须这样做
Note that switching to TCP will involve some refactoring of your code (it's a bit more complicated that just replacing SOCK_DGRAM
with SOCK_STREAM
), but in your case, you have to do it.
我并不是说UDP不好,但这不适用于您的情况.
I'm not saying UDP is bad, but it's not appropriate in your case.
这篇关于在python中发送/接收文件UDP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!