Hi,
I am creating my first app its a little server. I just wanted to know whats the best way to accept multiple connections but not be flooded, say 10 connections in 10 secounds then if flooded close the listener. Would threads or thread pool help me do this.
I added the Threadpool but not sure on how i should be using it for my application.
Please take a look at my code below and see what I need to do to make it secure and not get flooded.
Thanks
class Listener
{
public static TcpListener _listener;
private static TcpClient _client;
private static NetworkStream _clientStream;
public Listener(string ip, Int32 port)
{
ThreadPool.SetMaxThreads(50, 100);
ThreadPool.SetMinThreads(50, 50);
// Set the TcpListener IP & Port.
IPAddress localAddr = IPAddress.Parse(ip);
_listener = new TcpListener(localAddr, port);
}
public void Start() // Run this on a separate thread, as
{ // we did before.
_listener.Start();
Console.WriteLine("Starting server...\n");
Console.WriteLine("Listening on {0}:{1}...", Globals._localIP, Globals._port);
while (Globals._Listen)
{
try
{
if (!_listener.Pending())
{
Thread.Sleep(500); // choose a number (in milliseconds) that makes sense
continue; // skip to next iteration of loop
}
Globals._requestCounter += +1;
// Get client's request and process it for web request.
ProcessRequest();
}
catch (SocketException e)
{
// Listener Error.
}
catch (InvalidOperationException er)
{
}
}
_listener.Stop();
}
public static void Stop()
{
Globals._Listen = false;
}
}
static void Main(string[] args)
{
// Set listener settings.
var server = new Listener(Globals._localIP, Globals._port);
// Start the listener on a parallel thread:
Thread listenerThread = new Thread(server.Start);
listenerThread.Start();
Thread.Sleep(500);
}