I need to handle http requests and the best way I found was using a ThreadPool. Please dont recommend using a finished library, because when I try to do something similar, there will be the same problem(s)!
When try a DDOS-Tool on my own webserver the cpu usage gets high and the memory increases incredible fast!
When I stop the tool the memory usage still increases (see screenshot)!
I want the program to decrease its memory usage after the DDOS-Tool has been stopped.
But unfortunately it does not!
Here is my code: You can try it. It does not need any libraries!
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace Webserver
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(81);
tcpListener.Start();
while (true)
ThreadPool.QueueUserWorkItem(DoWork, tcpListener.AcceptTcpClient());
}
static void DoWork(object arg)
{
try
{
using (TcpClient tcpClient = (TcpClient)arg)
{
tcpClient.ReceiveTimeout = 500;
tcpClient.SendTimeout = 500;
using (NetworkStream networkStream = tcpClient.GetStream())
{
networkStream.ReadTimeout = 500;
networkStream.WriteTimeout = 500;
List<string> headers = new List<string>();
using (StreamReader streamReader = new StreamReader(networkStream))
using (StreamWriter streamWriter = new StreamWriter(networkStream))
{
while (true)
{
string line = streamReader.ReadLine();
if (line == "") break;
else headers.Add(line);
}
Console.WriteLine(headers[0]);
streamWriter.WriteLine("HTTP/1.0 200 OK");
streamWriter.WriteLine("Server: Webserver");
streamWriter.WriteLine("Content-Type: text/html; charset=UTF-8");
streamWriter.WriteLine("");
streamWriter.WriteLine("Hello World!");
}
}
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
}
}
}
The red lines mark the timestamps when I started and stopped the ddos-Tool. As you can see, the memory still increases after the tool has been stopped.
I want my program to get down back to 17 MB memory usage as it was at the beginning.