开发者

Asynchronously send / receive fixed amount of data using tcp socket

开发者 https://www.devze.com 2023-02-09 08:33 出处:网络
In my application I do some asynchronous communication over a TCP socket. I don\'t like the fact that the send and receive operations (sync or async) of the Socket class are allowed to finish before

In my application I do some asynchronous communication over a TCP socket.

I don't like the fact that the send and receive operations (sync or async) of the Socket class are allowed to finish before the requested number of bytes were transmitted. For example: when I want to read X bytes from the socket, I don't want to care about how many read operations are effectively needed to achieve this (in my application logic). I just want to be notified when it开发者_如何学JAVA's finished (or when an error occured).

It would be nice to have something like BeginSendFixed, EndSendFixed, BeginReceiveFixed and EndReceiveFixed. Those would behave exactly like BeginSend, EndSend, BeginReceive, EndReceive, but not call the callback before the requested number of bytes was transmitted.

I'm thinking about implementing this by myself, based on:

http://msdn.microsoft.com/en-us/magazine/cc163467.aspx

In the DoTaskHelper function I would call as many (synchronous) Send or Receive until all data is transmitted.

Is this the way to go or is there a different (better) way to hide the need for multiple sends / receives from my application logic?


I recommend using the TaskCompletionSource class for this. This has the advantage of not burning a thread just waiting for I/O. It would probably be easier to wrap the existing (asynchronous) APIs as Tasks first, and then create your API using TaskCompletionSource.

Note that TaskCompletionSource was added in .NET 4. If you're not on that platform yet, then I recommend marshaling the completion routines to a UI thread (which can be easily done using the Event-based Asynchronous Pattern socket wrappers in Nito.Async.Sockets), and then putting them through a parser that is specific to your protocol (an example of which is on my blog).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号