I am in the process of updating an app that is going from supporting a single connection to being able to support numerous connections. I have figured that using the Task Parallel Library may be the best way to go about this in terms of creating and managing the multiple sockets there will be. As such, I have begun to write some code and have come across a possible issue while debugging. It seems that some of my tasks that I create to set up the connections never complete and am wondering if I am utilizing TPL correctly or if it is something else. If I debug the code, it appears as if only one task in the collection actually contains a Socket. Any assistance is appreciated. Here is the code from a sandbox console application.
Main:
static void Main(string[] args)
{
Console.WriteLine("Creating connections.....");
var sockets = CreateListeners(5);
Console.WriteLine("Socket Info:");
foreach (var socket in sockets)
{
if (socket.Result != null)
{
var con = socket.Result;
IPEndPoint ipep = (IPEndPoint)con.LocalEndPoint;
string port = ipep.Port.ToString();
Console.WriteLine("Socket #{0} - Listening on Port {1}:", socket.Id.ToString(), port);
}
}
Console.WriteLine("Press any key to exit..");
Console.ReadLine();
}
Function that creates a list of Tasks:
private static List<Task<Socket>> CreateListeners(int numberToCreate)
{
var sockets = new List<Task<Socket>>();
for (int n = 0; n < numberToCreate; n++)
{
var currentSocket = Task<Socket>.Factory.StartNew(() => CreateSocketConnection(n));
sockets.Add(currentSocket);
}
return sockets;
}
Function that creates a single socket connection..
private static Socket CreateSocketConnection(int port)
{
try
{
IPAddress ipAddress = null;
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
if (Socket.OSSupportsIPv6)
{
ipAddress = ipHostInfo.AddressList[1];
}
else
{
ipAddress = ipHostInfo.AddressList[0];
}
//Create a new connection on specified port
IPEndPoint endPoint = new IPEndPoint(ipAddress, port+6000);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endPoint);
//listener.Blocking = false;
listener.Listen(500);
return listener;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
return null;
}