This code outputs "8096" 13 times as expected (ceil(100,000/8096) = 13)
But then after the while loops in both functions nothing else runs but program finishes, the 2 console.writlelines after them don't get run (does work printing before, just not after the while loop)
Here is my code:
Tcpclient function:
public static async void Main()
{
using TcpClient client = new TcpClient("localhost",50000);
using NetworkStream stream = client.GetStream();
byte[] data = RandomNumberGenerator.GetBytes(100000);
await stream.WriteAsync(data,0,data.Length);
byte[] bytes = new byte[8096];
int i;
while((i = await stream.ReadAsync(bytes, 0, bytes.Length))>0)
{
Console.WriteLine(i);
}
Console.WriteLine("this doesnt get printed");
client.Close();
return;
}
tcplistener function:
public static async void Main()
{
try
{
TcpListener server = new TcpListener(IPAddress.Any,50000);
server.Start();
using TcpClient client = await server.AcceptTcpClientAsync();
using NetworkStream stream = client.GetStream();
byte[] bytes = new byte[8096];
byte[] return_bytes = new byte[8096];
int i;
while((i = await stream.ReadAsync(bytes, 0, bytes.Length))>0)
{
await stream.WriteAsync(return_bytes,0,return_bytes.Length);
}
Console.WriteLine("this doesn't get printed");
client.Close();
server.Stop();
}
catch(Exception ex)
{
Console.WriteLine("port already in use");
}
}
Tried making it synchronous and putting them in threads but that didn't work
You need to hand off the reading to another task or thread, as otherwise the client is blocked waiting for the listener, which in turn is blocked waiting to echo to the client, which is still blocked trying to send.
See also @StephenCleary's blog for more.