使用python socket时接收所有数据 [英] Receive all of the data when using python socket

查看:507
本文介绍了使用python socket时接收所有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用套接字连接到一个简单的服务器来接收一些数据:

I am using socket to connect to a simple server to receive some data:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = "X.X.X.X"
port = Y
s.connect((host,port))

data = s.recv(512)
print data

未收到所有预期的接收数据;其中一些被切断了.因此,我需要对接收到的数据执行的任何操作都将被丢弃.

Not all of the expected received data is received; some of it is cut off. So any operations that I need to perform on the received data is thrown off.

我尝试使用 s.settimeout(1) 并将套接字置于非阻塞模式.奇怪的是,它在 ipython 中工作得很好.

I've tried using s.settimeout(1) and putting the socket in non-blocking mode. Strangely, it works just fine in ipython.

推荐答案

即使 512 字节从服务器发送到客户端,如果它们是通过多个数据包发送的,并且该数据包设置了 TCP Push 标志,则内核将停止缓冲并将数据移交给用户空间,即您的应用程序.

Even if 512 bytes are sent from the server to the client, if they're sent through multiple packets, and that one packet has TCP Push flag set, the kernel will stop buffering and hand over the data to userland, ie, your application.

您应该循环 data = s.recv(512) 并打印数据.我什至会删除无用的512".

You should loop on data = s.recv(512) and print data. I'd even remove the '512', which is useless.

while True:
    if not data: break
    data = s.recv()
    print data

这篇关于使用python socket时接收所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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