I need to listen to multiple ports using TcpListener and i need TcpListener to accept multiple connections and work with each one individually, this is the code i wrote but as you see it just listen to first port then goes to while(true)
and listen to all the connection that comes to that port. any idea how can i how can i listen to multiple port for multiple connections?
private static async Task TcpServerAsync()
{
try
{
IPAddress ip;
if (!IPAddress.TryParse(ConfigurationManager.AppSettings["ipAddress"], out ip))
{
Console.WriteLine("Failed to get IP address, service will listen for client activity on all network interfaces.");
ip = IPAddress.Any;
}
foreach (Ports port in Ports.GetValues(typeof(Ports)))
{
Log.Info("Starting listener...");
var tcpListener = new TcpListener(ip, (int)port);
tcpListener.Start();
Log.Info("Listening...");
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(10000000);
while (true)
{
TcpClient client = await tcpListener.AcceptTcpClientAsync();
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
HandleByPortNumber(client, (int)port);
}
}
}
catch (Exception ex)
{
Log.Info("Error Happened : " + ex + ex.InnerException);
}
}
and
public static void HandleByPortNumber(TcpClient client , int portNumber)
{
switch (portNumber)
{
case (int)Ports.Teltonica:
var cw = new Teltonika.TcpClientService(client);
ThreadPool.UnsafeQueueUserWorkItem(x => ( (Teltonika.TcpClientService)x).Run(), cw);
break;
case (int)Ports.OBDTracker:
break;
}
}
and
public enum Ports
{
Teltonica = 3000,
OBDTracker = 3001
}