简体   繁体   English

Python 套接字接收函数

[英]Python socket recv function

In the python socket module recv method socket.recv(bufsize[, flags]) docs here , it states:在 python 套接字模块 recv 方法socket.recv(bufsize[, flags]) docs here 中,它指出:

Receive data from the socket. The return value is a bytes object representing the data received.
The maximum amount of data to be received at once is specified by bufsize.

I'm aware that bufsize represents the MAX amount of data received at once, and that if the amount of data received is LESS than bufsize, that means that the number of bytes sent by socket on the other end is less than bufsize我知道bufsize表示一次接收的最大数据量,如果接收到的数据量小于bufsize,那意味着另一端socket发送的字节数小于bufsize

Is it possible that the data returned from the 1st call to socket.recv(bufsize) is < bufsize but there is still data left in the network buffer?是否有可能从第一次调用socket.recv(bufsize)返回的数据 < bufsize但网络缓冲区中仍有数据?

Eg.例如。

data = socket.recv(10)
print(len(data))       # outputs 5
data = socket.recv(10) # calling `socket.recv(10)` returns more data without the
                       # socket on the other side doing `socket.send(data)`

Can a scenario in the example ever occur and does this apply for unix domain sockets as well as regular TCP/IP sockets?示例中的场景是否会发生,这是否适用于 unix 域套接字以及常规 TCP/IP 套接字?

The real problem in network communication is that the receiver cannot control when and how the network delivers the data.网络通信中的真正问题是接收方无法控制网络何时以及如何传送数据。

If the size of the data returned by recv is less than the requested size, that means that at the moment of the recv call , no more data was available in the local network buffer.如果recv返回的数据大小小于请求的大小,这意味着recv调用的那一刻,本地网络缓冲区中没有更多数据可用。 So if you can make sure that:因此,如果您可以确保:

  • the sender has stopped sending data发送方已停止发送数据
  • the network could deliver all the data网络可以提供所有数据

then a new revc call will block.然后一个新的revc调用将被阻塞。

The problem is that in real world cases, you can never make sure of the two above assumptions.问题在于,在现实世界的情况下,您永远无法确定上述两个假设。 TCP is a stream protocol, which only guarantees that all sent bytes will go to the receiver and in correct order. TCP 是一种流协议,它只保证所有发送的字节都会以正确的顺序到达接收器。 But if offers no guarantee on the timing, and sent packets can be fragmented or re-assembled by the network (starting from the network TCP stack on the sender and ending at the reciever TCP stack)但是,如果提供的定时没有保证,和发送的数据包可以被分片或由网络重新组装(从发送者的网络TCP栈开始并在reciever TCP堆栈结束)

Found a similar post that follows up on this: How can I reliably read exactly n bytes from a TCP socket?找到了一个类似的帖子: 如何从 TCP 套接字可靠地读取 n 个字节?

Basically use socket.makefile() to return a file object and call read(num_bytes) to return exactly the amount requested, else block.基本上使用socket.makefile()返回一个文件对象并调用read(num_bytes)以准确返回请求的数量,否则阻止。

fh = socket.makefile(mode='b')
data = fh.read(LENGTH_BYTES)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM