// We use a wait handle here to synchronize the client threads with the main thread.
private static AutoResetEvent _waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
// Start the server on port 1337
StartServer(1337);
}
private static void StartServer(int port)
{
// Create a connection listener
var listener = new TcpListener(IPAddress.Any, port);
try
{
// Start the listener
listener.Start();
while (true)
{
// Wait for a connection, and defer connection handling asynchronously.
listener.BeginAcceptTcpClient(new AsyncCallback(HandleAsyncConnection), listener);
_waitHandle.WaitOne();
_waitHandle.Reset();
}
}
catch (SocketException ex)
{
// Handle socket errors or any other exception you deem necessary here
}
finally
{
// Stop the server.
listener.Stop();
}
}
private static void HandleAsyncConnection(IAsyncResult state)
{
// Get the listener and the client references
var listener = (TcpListener)state.AsyncState;
using (var tcpClient = listener.EndAcceptTcpClient(state))
{
// Signal the main thread that we have started handling this request.
// At this point the server is ready to handle another connection, and no amount
// of tomfoolery on the client's side will prevent this.
_waitHandle.Set();
// Declare buffers
var inBuff = new byte[tcpClient.ReceiveBufferSize];
var outBuff = new byte[tcpClient.SendBufferSize];
// Get the connection stream
using (var stream = tcpClient.GetStream())
{
try
{
// Read some data into inBuff
stream.Read(inBuff, 0, tcpClient.ReceiveBufferSize);
// Do something with the data here, put response in outBuff...
// Send response to client
stream.Write(outBuff, 0, outBuff.Length);
}
catch (SocketException ex)
{
// Handle socket errors or any other exception you deem necessary here
}
}
}
}