I want to create sending a Socket message through TAP via async / wait.
After reading this answer and this, I decided to create a fully working sample:
So what I tried:
I took the TAP extension methods from here (everything is fine): and I am testing it in the cmd console:
Recipient Code
public static class SocketExtensions { public static Task<int> ReceiveTaskAsync(this Socket socket, byte[] buffer, int offset, int count) { return Task.Factory.FromAsync<int>( socket.BeginReceive(buffer, offset, count, SocketFlags.None, null, socket), socket.EndReceive); } public static async Task<byte[]> ReceiveExactTaskAsync(this Socket socket, int len) { byte[] buf = new byte[len]; int totalRead = 0; do{ int read = await ReceiveTaskAsync(socket, buf, totalRead, buf.Length - totalRead); if (read <= 0) throw new SocketException(); totalRead += read; }while (totalRead != buf.Length); return buf; } public static Task ConnectTaskAsync(this Socket socket, string host, int port) { return Task.Factory.FromAsync( socket.BeginConnect(host, port, null, null), socket.EndConnect); } public static Task SendTaskAsync(this Socket socket, byte[] buffer) { return Task.Factory.FromAsync<int>( socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, null, socket), socket.EndSend); } } static void Main() { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.ConnectTaskAsync("127.0.0.1", 443); var buf1 = s.ReceiveExactTaskAsync(100);
Sender Code:
// use same extension method class like above ....^ void Main() { Socket s = new Socket(SocketType.Stream , ProtocolType.Tcp); s.ConnectTaskAsync( "127.0.0.1" , 443); s.SendTaskAsync(Encoding.UTF8.GetBytes("hello")); s.Close(); Console.ReadLine(); }
Sorry, I removed async from main, since im tested it in the console.
Question,
According to the link above, the code should work
However, I am not getting an exception, and it just hangs on this line:
Console.Write(Encoding.UTF8.GetString(buf1.Result));
(First I start the receiver, then I start the sender)
What am I missing?