コード例 #1
0
        // does not reach here.
        /// <summary>
        /// The contract is similar to
        /// <see cref="SocketChannel.Connect(System.Net.EndPoint)"/>
        ///
        /// with a timeout.
        /// </summary>
        /// <seealso cref="SocketChannel.Connect(System.Net.EndPoint)"/>
        /// <param name="channel">
        /// - this should be a
        /// <see cref="SelectableChannel"/>
        /// </param>
        /// <param name="endpoint"/>
        /// <exception cref="System.IO.IOException"/>
        internal static void Connect(SocketChannel channel, EndPoint endpoint, int timeout
                                     )
        {
            bool blockingOn = channel.IsBlocking();

            if (blockingOn)
            {
                channel.ConfigureBlocking(false);
            }
            try
            {
                if (channel.Connect(endpoint))
                {
                    return;
                }
                long timeoutLeft = timeout;
                long endTime     = (timeout > 0) ? (Time.Now() + timeout) : 0;
                while (true)
                {
                    // we might have to call finishConnect() more than once
                    // for some channels (with user level protocols)
                    int ret = selector.Select((SelectableChannel)channel, SelectionKey.OpConnect, timeoutLeft
                                              );
                    if (ret > 0 && channel.FinishConnect())
                    {
                        return;
                    }
                    if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.Now())) <= 0))
                    {
                        throw new SocketTimeoutException(TimeoutExceptionString(channel, timeout, SelectionKey
                                                                                .OpConnect));
                    }
                }
            }
            catch (IOException e)
            {
                // javadoc for SocketChannel.connect() says channel should be closed.
                try
                {
                    channel.Close();
                }
                catch (IOException)
                {
                }
                throw;
            }
            finally
            {
                if (blockingOn && channel.IsOpen())
                {
                    channel.ConfigureBlocking(true);
                }
            }
        }