[英]how to write/send a specific number of bytes to a socket totally but not partially?
I want to write a specific number of bytes to a socket, 我想给套接字写一个特定的字节数,
n=write(sock_fd, buf, len);
if n<len
, I would rather no bytes are written into the socket, is it possible or not? 如果n<len
,我宁愿没有字节写入套接字,是否可能? thanks! 谢谢!
If the socket is in blocking mode then, as EJP (+1) says, write() will not return until len bytes have been written to the socket's outgoing buffer. 如果套接字处于阻塞模式,那么,正如EJP(+1)所说, write()将不会返回,直到len字节已写入套接字的传出缓冲区。
However, it's important to note that that doesn't tell you anything about how many bytes have been received at the receiving end of the connection. 但是,重要的是要注意,这并不能告诉您在连接的接收端收到了多少字节。 In fact for small values of len when write() returns no data has been sent at all (yet). 事实上,当write()返回时,对于len的小值,根本没有发送任何数据。 And when the other end calls read() it will block until some data has arrived, but not necessarily len bytes. 当另一端调用read()时 ,它将阻塞,直到某些数据到达,但不一定是len字节。 If you want to read len bytes then you may have to keep calling read() until you have got them all. 如果你想读取len字节,那么你可能必须继续调用read()直到你得到它们。
The only real way to know what's actually happened and when it finished is to have some sort of message being returned from the other end of the socket to say that everything has now arrived. 知道实际发生了什么以及何时完成的唯一真正方法是从套接字的另一端返回某种消息,说现在一切都已到达。 A confirmatory return from write() is not enough by itself. 来自write()的确认回报本身是不够的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.