- Is using TPL to create a collection of Sockets overkill or is there a better way to create multiple sockets?
- 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();
- }
- 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;
- }
- 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;
- }
- Task<Socket>.Factory.StartNew(start, CancellationToken.None,
- TaskCreationOptions.LongRunning, // The interpretation depends on scheduler
- TaskScheduler.Default // The default one place them in their own thread
- );
- throw ex;
- throw; // To re-throw the same exception
- throw new Exception("bla", ex); // To specify a new message, or change the
- // exception type. A new stack trace is created
- // but you can still access the original one
- // using InnerException