gpt4 book ai didi

c# - C#Socket.Send(): does it send all data or not?

转载 作者:行者123 更新时间:2023-12-03 12:03:31 28 4
gpt4 key购买 nike

我从Richard Blum的一本书《 C#网络编程》中读到有关套接字的信息。以下摘录指出,不保证Send()方法可以发送所有传递给它的数据。

byte[] data = new byte[1024];
int sent = socket.Send(data);

On the basis of this code, you might be tempted to presume that the entire 1024-byte data buffer was sent to the remote device... but this might be a bad assumption. Depending on the size of the internal TCP buffer and how much data is being transferred, it is possible that not all the data supplied to the Send() mehtod was actually sent.



但是,当我查看Microsoft文档 https://msdn.microsoft.com/en-us/library/w93yy28a(v=vs.110).aspx时说:

If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent, unless a time-out was set



那是什么呢?该书于2004年出版,自那以后有没有改变?

我打算使用异步套接字,所以我的下一个问题是BeginSend()是否发送所有数据?

最佳答案

您所要做的就是阅读与引用相同的段落的其余部分。同一句话中的报价甚至有异常(exception)。

If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent, unless a time-out was set by using Socket.SendTimeout. If the time-out value was exceeded, the Send call will throw a SocketException. In nonblocking mode, Send may complete successfully even if it sends less than the number of bytes in the buffer. It is your application's responsibility to keep track of the number of bytes sent and to retry the operation until the application sends the bytes in the buffer.



对于 BeginSend,还描述了该行为:

Your callback method should invoke the EndSend method. When your application calls BeginSend, the system will use a separate thread to execute the specified callback method, and will block on EndSend until the Socket sends the number of bytes requested or throws an exception.



这不是一个很好的设计,并且破坏了回调的全部要点!考虑改用 SendAsync (然后您仍然需要检查 BytesTransferred属性)。

关于c# - C#Socket.Send(): does it send all data or not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49622057/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com