C# Socket.BeginSend AsyncCallback 行为(超时?)
这是一个我不太明白的异步套接字场景...我有 2 个 Tcp 套接字、一个客户端套接字和一个客户端套接字。服务器套接字。我的服务器套接字已绑定&监听端口。
我的客户端套接字连接到服务器套接字(使用 BeginConnect / EndConnect)。然后我使用 BeginSend() 向服务器发送一条消息。在服务器端,我不执行 Receive() 或 BeginReceive()。
发生的情况是,为 BeginSend 调用指定的 AsyncCallback 被调用并返回。它的 IAsyncResult 告诉我它已完成 &对 Socket.EndSend() 的调用不会引发任何异常...
是否有一些我没有得到的东西,或者只有当 BeginSend 调用实际向服务器发送某些内容时才应该调用我的 AsyncCallback(即:调用的回调)服务器收到所有字节后)?如果服务器上没有完成接收,那么在 sendtimeout 到期后不应该调用我的回调吗?然后我对 Socket.EndSend 的调用会引发异常吗?
谢谢
Here is a scenario with asynchronous sockets that I dont't quite understand... I have 2 Tcp sockets, a client socket & a server socket. My server socket is bound & listening on a port.
My client sockets connect to the server socket (using BeginConnect / EndConnect). I then send a message to the server using BeginSend(). On the server side, I don't do a Receive() or BeginReceive().
What happens is that my AsyncCallback specified for my BeginSend call gets invoked & its IAsyncResult tells me that it completed & the call to Socket.EndSend() does not raise any exception...
Is there something that I don't get or shouldn't my AsyncCallback be called only if the BeginSend call actually sends something to the server (ie.: callback called after the server has received all bytes)? If there was no receive done on the server, shouldn't my callback be called after the sendtimeout expires and my call to Socket.EndSend then would raise an exception?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,TCP/IP 会为您处理这一切。连接两端都有缓冲区,用于保存数据直到可以接收数据。如果没有缓冲,发送聊天通信时可能会出现可怕的延迟。
把它想象成邮寄一封信。它会一直放在您的邮箱中,直到邮递员取走它。一旦发生这种情况,它就会被发送。还没有收到。它可能正在运输途中,也可能在他们的邮箱中等待他们阅读。
因此,在 BeginSend 之后获取回调只会告诉您它已发送。确定对方已收到并处理数据的唯一方法是请求回复一段时间的确认。
Nope, TCP/IP handles all this for you. There's buffers at both sides of the connection that will hold the data until it can be received. Without the buffering, there would probably be horrible latency when sending chatty communication.
Think of it like mailing a letter. It sits in your mailbox until the mail man picks it up. Once that happens, it's been sent. It hasn't yet been received. It could be in transit, or it could be waiting in their mailbox for them to read.
So getting the callback after BeginSend only tells you that it was sent. The only way to know for sure that the other side received and processed the data is to request some time of acknowledgement back.