I am trying to make a simple server application to learn the basics of multi threaded server programming in c#. The basic idea is simple: the client connects to the server and sends: "get time" to receive to current time of the server. All of the tcplistener threads and sockets should be running on seperate threads. I am not sure why, but when the application finishes initializing all of the threads, the console app closes.
Here is the server code:
class Program
{
static public int minPort;
static public int maxPort;
static int openPort = 0;
static byte[] sendData = new byte[1024];
static TcpListener[] listeners;
static Thread[] connectionThreads;
static void Main()
{
Console.Write("What do you want your minimum port to be? ");
minPort = Convert.ToInt32(Console.ReadLine());
Console.Write("What do you want your maximum port to be? ");
maxPort = Convert.ToInt32(Console.ReadLine());
//init
ThreadStart streamThreadStart = new ThreadStart(DataStream);
openPort = maxPort - minPort;
listeners = new TcpListener[maxPort - minPort];
connectionThreads = new Thread[maxPort - minPort];
for (int i = 0; i == maxPort - minPort; i++)
{
listeners[i] = new TcpListener(IPAddress.Any, minPort + i);
connectionThreads[i] = new Thread(streamThreadStart);
Thread.Sleep(10);
openPort = openPort + 1;
}
}
static void DataStream()
{
int port = openPort;
byte[] receiveData = new byte[1024];
listeners[openPort].Start();
Socket socket = listeners[port].AcceptSocket();
NetworkStream stream = new NetworkStream(socket);
while (true)
{
socket.Receive(receiveData);
Console.WriteLine("Received: " + BitConverter.ToString(receiveData));
socket.Send(parseCommand(receiveData));
}
}
static byte[] parseCommand(byte[] input)
{
string RCommand = BitConverter.ToString(input);
string SCommand;
if (RCommand == "get time")
{
SCommand = DateTime.Now.ToUniversalTime().ToString();
}else
{
SCommand = "Unknown Command, please try again";
}
byte[] output = Encoding.ASCII.GetBytes(SCommand);
return output;
}
}