如何检查是否使用Python中的TCP套接字接收了所有数据 [英] How to check if all data are received with a TCP Socket in Python

查看:413
本文介绍了如何检查是否使用Python中的TCP套接字接收了所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python作为编程语言从TCP连接(仅客户端)获取数据

I am trying to get data from a TCP Connection (client side only) using Python as programming language,

但是,我看到所有数据都没有收到一次,并且在接收过程的中间被削减了……我可以在论坛上看到TCP不能以正确的顺序发送数据(这有点随机,链接: Python套接字接收-传入数据包始终具有不同的大小),我错了吗?

However, I could see that all data are not received in once and are cut in the middle of the receiving process ... I could see on forums that TCP does not send data in the correct order (it is a bit random, link: Python socket receive - incoming packets always have a different size), am I wrong ?

我的问题是是否有办法确保我正确接收了所有数据?

My question is if there is anyway to make sure that I correctly received all data?

在此先感谢您的帮助和答复,

Thanks in advance for your help and replies,

PS:我已经增加了socket.recv()的缓冲区大小,但是仍然面临着同样的问题...而且我只在CentOS下工作

PS: I already increased the buffer size of socket.recv(), but still facing the same issue ... And I am only working under CentOS

编辑:(无法回答我自己的问题:(这个论坛上还是初学者:))

(couldn't reply to my own question :( Still beginner on this forum :) )

非常感谢您的答复,实际上我没有担心TCP连接:)

Thanks a lot for your reply, indeed I don't have to worry about the TCP connection :)

经过更多调查,我终于找到了解决方法……(我在搜索几天后才在这里发布问题) ,

After investigating more, I could finally find the solution ... (I was searching for a few days before posting my question here),

如果有人需要答案,在python中,您必须等待完整的消息,否则消息会被剪切,因此这意味着:

If anyone needs an answer, in python you must wait for the full message, otherwise the message can be cut, so this means:

data = s.recv(1024,socket.MSG_WAITALL)->'s'是在python代码中创建的套接字对象,

data = s.recv(1024, socket.MSG_WAITALL) --> 's' is a socket object created in the python code,

亲切的问候

推荐答案

使用套接字API,您不必担心TCP(排序,重新传输等),操作系统已解决了所有这些问题。唯一的事情是 socket.recv()将最多返回 n个字节。这意味着不能保证每次阻塞读取都会收到n个字节。因此,您必须循环阅读,直到收到所需的字节数为止。

using the sockets API, you do not have to worry about TCP (the ordering, retransmissions and whatnot), it's all been taken care of by the OS. The only thing is that socket.recv() will return at most n bytes. This means that it is not guaranteed that you will receive n bytes at each blocking read. So, you must read in a loop until you have received the desired amount of bytes.

这篇关于如何检查是否使用Python中的TCP套接字接收了所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆