如何通过套接字发送/接收数据文件?
我正在使用 Python 编写套接字编程,以便通过 TCP 发送/接收文件。
当我发送/接收数据时,我发现它既没有发送也没有接收文件的部分。
这里是根据缓冲区的大小发送一部分数据的部分。
msg[i] = file[i].read()
file[i].close()
while 1:
tdata[i], msg[i] = msg[i][:buf], msg[i][buf:]
c.send(tdata[i])
if len(msg[i]) < buf:
break
请帮助我如何完整地发送/接收整个数据。
I am writing a socket programming with Python in order to send/receive a file over TCP.
While I am sending/receiving data, I figured out it neither sent nor received the part of files.
Here is a part to send a part of data based on the size of the buffer.
msg[i] = file[i].read()
file[i].close()
while 1:
tdata[i], msg[i] = msg[i][:buf], msg[i][buf:]
c.send(tdata[i])
if len(msg[i]) < buf:
break
Please help me out how to send/receive the whole data completely.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
len(msg[i])
len(msg[i])
时,它将停止发送。 buf
,所以数据末尾可能会丢失。如果您想发送所有 msg[i],最好这样做:
或者一次性发送:
请注意
send()
将返回实际发送的字节数(因为它不会'不一定发送全部),因此如果您想发送全部(通常是这种情况),请使用sendall()
。It will stop sending when
len(msg[i]) < buf
, so the end of data may be missing.If you want to send all of msg[i], it's better to do:
or just send it in one go:
Note that
send()
will return how many bytes were actually sent (because it won't necessarily send all of them), so if you want to send all (which is usually the case) usesendall()
instead.我会尝试这样的事情:
这就是 SimpleHTTPServer 模块的做法。
I would try something like this:
This is how the SimpleHTTPServer module does it.