See example here, the
client.Close(); must be outside the While loop:
TcpListener Class (System.Net.Sockets) | Microsoft Docs[
^]
With a While loop like this:
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
)
client.Close();
For the server to know when to stop listening, your client could send a special message, but this would be a bit unusual as servers normally keep listening.