Example #1
0
        static void Main(string[] args)
        {
            int Port = ListeningPort;

            // Verify arguments
            if (args.Length < 1 || (args[0] != "IPv4" && args[0] != "IPv6"))
            {
                Console.WriteLine("Usage: TCPServer.exe <IPv4 | IPv6> [port]");
                return;
            }
            if (args.Length >= 2)
            {
                Port = System.Convert.ToInt32(args[1].ToString());
            }

            try
            {
                Socket ListeningSocket;

                if (args[0] == "IPv4")
                {
                    // Create a new socket to listening for client connections.

                    ListeningSocket = new Socket(
                        AddressFamily.InterNetwork,
                        SocketType.Stream,
                        ProtocolType.IP);

                    // Setup a SOCKADDR_IN structure that will tell bind that we
                    // want to listen for connections on all interfaces using port
                    // 5150.

                    IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Any, Port);

                    ListeningSocket.Bind(LocalEndPoint);
                }
                else                 // IPv6
                {
                    // Create a new socket to listening for client connections.

                    ListeningSocket = new Socket(
                        AddressFamily.InterNetworkV6,
                        SocketType.Stream,
                        ProtocolType.IP);

                    IPv6EndPoint LocalEndPoint = new IPv6EndPoint(IPv6Address.Any, Port);

                    ListeningSocket.Bind(LocalEndPoint);
                }

                ListeningSocket.Listen(5);

                Console.WriteLine("Server started - Press RETURN to stop the server.");
                Console.WriteLine("Awaiting socket connections...");

                AcceptInfo AI = new AcceptInfo(ListeningSocket);

                for (int i = 0; i < MaxAsyncAccepts; i++)
                {
                    AI.ListeningSocket.BeginAccept(AI.AcceptCallback, AI);
                }

                Console.ReadLine();

                ListeningSocket.Close();
                AI.RemoveAllSockets();

                Console.WriteLine("Pending connections were closed - press RETURN to stop application");
                Console.ReadLine();
            }

            catch (SocketException err)
            {
                Console.WriteLine("Error: " + err.Message);
            }
        }