Exemple #1
0
        private Socket GetSocket(IPAddress ip, int port, AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, bool server)
        {
            Socket          socket = null;
            SocketException rex    = null;
            bool            error;
            var             tries = 0;

            do
            {
                tries++;
                try
                {
                    socket = new Socket(addressFamily, socketType, protocolType);

                    if (port == 0)
                    {
                        port = freePortProvider.GetFreePort();
                    }

                    bool success;
                    if (server)
                    {
                        socket.Bind(new IPEndPoint(ip, port));
                        socket.Listen(MaxPendingConnections);
                        success = true;
                    }
                    else
                    {
                        var result = socket.BeginConnect(ip, port, null, null);
                        success = result.AsyncWaitHandle.WaitOne(SocketConnectionTimeout, true);
                    }

                    error = !success;
                }
                catch (SocketException ex)
                {
                    rex   = ex;
                    error = true;
                }
            }while (error && tries < MaxTriesToGetSocket);

            if (error && tries == MaxTriesToGetSocket)
            {
                if (rex != null)
                {
                    throw rex;
                }
            }
            return(socket);
        }
        public Socket OpenPort()
        {
            var freePortProvider = new FreePortProvider();

            return(OpenPort(freePortProvider.GetFreePort()));
        }