send()是否总是发送整个缓冲区? [英] Does send() always send whole buffer?

查看:86
本文介绍了send()是否总是发送整个缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

send()应该返回发送的字节数或错误代码,但是我发现的所有示例仅使用错误代码对它进行检查,而不会使用发送的字节数进行检查.

send() shall return the number of bytes sent or error code, but all examples that I found check it only with error codes, but not with the number of bytes sent.

//typical example
int cnt=send(s,query,strlen(query),0);
if (cnt < 0) return(NULL);
//Hey, what about cnt < strlen(query)?

推荐答案

问:"send()"是否总是返回整个缓冲区?

Q: Does "send()" always return the whole buffer?

A:不,不一定.

摘自《 Beej指南》: * http://beej.us/guide/bgnet/html/multi /syscalls.html#sendrecv

From Beej's Guide: * http://beej.us/guide/bgnet/html/multi/syscalls.html#sendrecv

send()返回实际发送的字节数,这可能是 少于您告诉它发送的号码!看,有时候你告诉 发送一整块数据,它只是无法处理.会开火 尽可能多地删除数据,并信任您将其余的数据发送出去 之后.请记住,如果send()返回的值与 以len为单位的值,则取决于您发送其余的字符串.好的 消息是这样的:如果数据包很小(小于1K左右),它将 可能一口气将整个事情发送了出去.同样,-1为 错误返回,并将errno设置为错误号.

send() returns the number of bytes actually sent out—this might be less than the number you told it to send! See, sometimes you tell it to send a whole gob of data and it just can't handle it. It'll fire off as much of the data as it can, and trust you to send the rest later. Remember, if the value returned by send() doesn't match the value in len, it's up to you to send the rest of the string. The good news is this: if the packet is small (less than 1K or so) it will probably manage to send the whole thing all in one go. Again, -1 is returned on error, and errno is set to the error number.

问:"recv()"是否总是读取整个缓冲区?

Q: Does "recv()" always read the whole buffer?

A:不,绝对不是.您应该从不假定接收到的缓冲区是整个消息".或者假设您收到的消息来自 one single 消息.

A: No, absolutely not. You should never assume the buffer you've received is "the whole message". Or assume the message you receive is from one, single message.

这是一个很好的简短说明.它适用于Microsoft/C#,但适用于所有语言的 all 套接字I/O:

Here's a good, short explanation. It's for Microsoft/C#, but it's applicable to all sockets I/O, in any language:

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