I am learning C# and I started to learn about things like asynchronous programming, streams and sockets so I tried to experiment with those concepts and made a simple program which is technically two programs with one server side and one client side. the server side is waiting for incoming connection and the client connect to the server and then both client and server can send text to each other and the text will be visible on the other side.
server side:
class Program
{
static void Main(string[] args)
{
var client = Conection();
while (true)
{
var task1 = Read(client.Result);
var task2 = Write(client.Result);
while (!task1.IsCompleted && !task2.IsCompleted)
{
}
}
}
async static Task<TcpClient> Conection()
{
var ip = IPAddress.Parse("127.0.0.1");
var port = 23000;
TcpListener server = new TcpListener(ip, port);
server.Start();
var client = await server.AcceptTcpClientAsync();
return client;
}
async static Task Read(TcpClient cli)
{
var stream = cli.GetStream();
var reader = new StreamReader(stream);
char[] buff = new char[64];
await reader.ReadAsync(buff, 0, buff.Length);
string text = new string(buff);
Console.WriteLine(text);
}
async static Task Write(TcpClient cli)
{
var stream = cli.GetStream();
var writer = new StreamWriter(stream);
var message = await Task.Run(() => Console.ReadLine());
writer.WriteLine(message);
writer.Flush();
}
}
client side:
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
var client = new TcpClient();
client.Connect(ip, 23000);
var stream = client.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
while (true)
{
var task1 = Read(reader);
var task2 = Write(writer);
while(!task1.IsCompleted && !task2.IsCompleted)
{
}
}
}
async static Task Write(StreamWriter wr)
{
var str = await Task.Run(() => Console.ReadLine());
wr.Write(str);
wr.Flush();
}
async static Task Read(StreamReader reader)
{
var str = await reader.ReadLineAsync();
Console.WriteLine(str);
}
}
It works fine but something looks wrong when I check in the task manager, it looks like in the client side the RAM usage is constantly rising without stopping just after sending some short text from the client or server side and the CPU usage is more than 11% in both the client and the server side...
Can I make this code more efficient in terms of using RAM and CPU?, or I simply did it all in the wrong way?.