从套接字读取:是否保证至少获得x个字节? [英] Read from socket: Is it guaranteed to at least get x bytes?

查看:71
本文介绍了从套接字读取:是否保证至少获得x个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个罕见的错误,似乎是在读取套接字时发生的.

I have a rare bug that seems to occur reading a socket.

似乎,在读取数据的过程中,有时我只会得到一个1-3字节的数据包,比这个更大.

It seems, that during reading of data sometimes I get only 1-3 bytes of a data package that is bigger than this.

正如我从管道编程中学到的那样,只要发送方提供足够的数据,我总是会得到至少512个字节.

As I learned from pipe-programming, there I always get at least 512 bytes as long as the sender provides enough data.

我的发件人在发送任何内容时都至少要发送> = 4字节-所以我想在发送开始(!!)时一次至少要收到4个字节.

Also my sender does at least transmit >= 4 Bytes anytime it does transmit anything -- so I was thinking that at least 4 bytes will be received at once in the beginning (!!) of the transmission.

在所有99.9%的情况下,我的假设似乎都成立了……但是在极少数情况下,收到的字节数少于4个.在我看来,可笑的是,为什么网络系统应该这样做?

In 99.9% of all cases, my assumption seems to hold ... but there are really rare cases, when less than 4 bytes are received. It seems to me ridiculous, why the networking system should do this?

有人知道更多吗?

这是我使用的阅读代码:

Here is the reading-code I use:

mySock, addr = masterSock.accept()
mySock.settimeout(10.0)
result = mySock.recv(BUFSIZE)
# 4 bytes are needed here ...
...
# read remainder of datagram
...

发送方一次调用send发送完整的数据报.

The sender sends the complete datagram with one call of send.

整个工作都在localhost上进行-因此不涉及复杂的网络应用程序(路由器等). BUFSIZE至少为512,发送方至少发送4个字节.

the whole thing is working on localhost -- so no complicated network applications (routers etc.) are involved. BUFSIZE is at least 512 and the sender sends at least 4 bytes.

推荐答案

我假设您正在使用TCP. TCP是基于流的协议,不了解数据包或消息边界.

I assume you're using TCP. TCP is a stream based protocol with no idea of packets or message boundaries.

这意味着当您执行读取操作时,获得的字节数可能会少于请求的字节数.例如,如果您的数据为128k,则第一次读取可能只会得到24k,要求您再次读取才能获得其余数据.

This means when you do a read you may get less bytes than you request. If your data is 128k for example you may only get 24k on your first read requiring you to read again to get the rest of the data.

以C语言为例:

int read_data(int sock, int size, unsigned char *buf) {
   int bytes_read = 0, len = 0;
   while (bytes_read < size && 
         ((len = recv(sock, buf + bytes_read,size-bytes_read, 0)) > 0)) {
       bytes_read += len;
   }
   if (len == 0 || len < 0) doerror();
   return bytes_read;
}

这篇关于从套接字读取:是否保证至少获得x个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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