简体   繁体   English

如何将特定数量的字节写入/发送到套接字完全但不是部分?

[英]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! 谢谢!

  1. If you're using blocking mode, the condition can never arise: send() will block until all the data has been sent. 如果您正在使用阻止模式,则永远不会出现这种情况:send()将阻塞,直到所有数据都已发送。 This is not the way the documentation reads, but it's how all known implementations behave. 这不是文档读取的方式,但它是所有已知实现的行为方式。
  2. If you're talking about TCP, it doesn't make any difference anyway: it's a byte-steam protocol, not a datagram protocol. 如果你在谈论TCP,它无论如何都没有任何区别:它是一个字节 - 蒸汽协议,而不是数据报协议。
  3. If you're talking about UDP, it already behaves that way in non-blocking ,ode, and for blocking mode see (1). 如果你在谈论UDP,它已经在非阻塞,颂歌和阻塞模式中表现为那样,参见(1)。

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.

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