Opc.Ua.Bindings.TcpMessageSocket.BeginConnect C# (CSharp) Method

BeginConnect() public method

Connects to an endpoint.
public BeginConnect ( Uri endpointUrl, EventHandler callback, object state ) : Task
endpointUrl System.Uri
callback EventHandler
state object
return Task
        public async Task<bool> BeginConnect(Uri endpointUrl, EventHandler<SocketAsyncEventArgs> callback, object state)
        {
            if (endpointUrl == null) throw new ArgumentNullException("endpointUrl");

            if (m_socket != null)
            {
                throw new InvalidOperationException("The socket is already connected.");
            }

            // Get DNS host information.
            IPAddress[] hostAdresses = await Dns.GetHostAddressesAsync(endpointUrl.DnsSafeHost);

            // try IPv4 and IPv6 address
            IPAddress addressV4 = null;
            IPAddress addressV6 = null;

            foreach (IPAddress address in hostAdresses)
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    if (addressV6 == null)
                    {
                        addressV6 = address;
                    }
                }
                if (address.AddressFamily == AddressFamily.InterNetwork)
                {
                    if (addressV4 == null)
                    {
                        addressV4 = address;
                    }
                }
                if ((addressV4 != null) && (addressV6 != null))
                {
                    break;
                }
            }

            SocketError error = SocketError.NotInitialized;
            TaskCompletionSource <SocketError> tcs = new TaskCompletionSource<SocketError>();
            SocketAsyncEventArgs argsV4 = null;
            SocketAsyncEventArgs argsV6 = null;
            m_socketResponses = 0;

            lock (m_socketLock)
            {
                // ensure a valid port.
                int port = endpointUrl.Port;

                if (port <= 0 || port > UInt16.MaxValue)
                {
                    port = Utils.UaTcpDefaultPort;
                }

                // create sockets if IP address was provided
                if (addressV6 != null)
                {
                    argsV6 = new SocketAsyncEventArgs();
                    argsV6.UserToken = state;
                    m_socketV6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
                    argsV6.RemoteEndPoint = new IPEndPoint(addressV6, port);
                    m_socketResponses++;
                    argsV6.Completed += (o, e) =>
                    {
                        lock (m_socketLock)
                        {
                            m_socketResponses--;
                            if (m_socketV6 != null)
                            {
                                if (m_socket == null &&
                                    (m_socketResponses == 0 || e.SocketError == SocketError.Success))
                                {
                                    m_socket = m_socketV6;
                                    tcs.SetResult(e.SocketError);
                                }
                                else
                                {
                                    m_socketV6.Dispose();
                                    e.UserToken = null;
                                }
                                m_socketV6 = null;
                            }
                            else
                            {
                                e.UserToken = null;
                            }
                        }
                    };
                    argsV6.Completed += callback;
                }
                if (addressV4 != null)
                {
                    argsV4 = new SocketAsyncEventArgs();
                    argsV4.UserToken = state;
                    m_socketV4 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    argsV4.RemoteEndPoint = new IPEndPoint(addressV4, port);
                    m_socketResponses++;
                    argsV4.Completed += (o, e) =>
                    {
                        lock (m_socketLock)
                        {
                            m_socketResponses--;
                            if (m_socketV4 != null)
                            {
                                if (m_socket == null &&
                                    (m_socketResponses == 0 || e.SocketError == SocketError.Success))
                                {
                                    m_socket = m_socketV4;
                                    tcs.SetResult(e.SocketError);
                                }
                                else
                                {
                                    m_socketV4.Dispose();
                                    e.UserToken = null;
                                }
                                m_socketV4 = null;
                            }
                            else
                            {
                                e.UserToken = null;
                            }
                        }
                    };
                    argsV4.Completed += callback;
                }

                bool connectV6Sync = true;
                bool connectV4Sync = true;
                if (m_socketV6 != null)
                {
                    connectV6Sync = !m_socketV6.ConnectAsync(argsV6);
                    if (connectV6Sync)
                    {
                        // I/O completed synchronously
                        callback(this, argsV6);
                        error = argsV6.SocketError;
                    }
                }
                if (m_socketV4 != null && error != SocketError.Success)
                {
                    connectV4Sync = !m_socketV4.ConnectAsync(argsV4);
                    if (connectV4Sync)
                    {
                        // I/O completed synchronously
                        callback(this, argsV4);
                        error = argsV4.SocketError;
                    }
                }

                if (connectV4Sync && connectV6Sync)
                {
                    return (error == SocketError.Success) ? true : false;
                }
            }

            error = await tcs.Task;

            return (error == SocketError.Success) ? true : false;
        }

Usage Example

コード例 #1
0
ファイル: TcpClientChannel.cs プロジェクト: zryska/UA-.NET
        /// <summary>
        /// Called when it is time to do a handshake.
        /// </summary>
        private void OnScheduledHandshake(object state)
        {
            try
            {
                // Utils.Trace("Channel {0}: Scheduled Handshake Starting: TokenId={1}", ChannelId, CurrentToken.TokenId);

                lock (DataLock)
                {
                    // check if renewing a token.
                    TcpChannelToken token = state as TcpChannelToken;

                    if (token == CurrentToken)
                    {
                        Utils.Trace("TCP CHANNEL {0}: Attempting Renew Token Now: TokenId={1}", ChannelId, token.TokenId);

                        // do nothing if not connected.
                        if (State != TcpChannelState.Open)
                        {
                            return;
                        }

                        // begin the operation.
                        m_handshakeOperation = BeginOperation(Int32.MaxValue, m_HandshakeComplete, token);

                        // send the request.
                        SendOpenSecureChannelRequest(true);
                        return;
                    }
                    
                    // must be reconnecting - check if successfully reconnected.
                    if (!m_reconnecting)
                    {
                        return;
                    }
                    
                    Utils.Trace("Channel {0}: Attempting Reconnect Now.", ChannelId);

                    // cancel any previous attempt.
                    if (m_handshakeOperation != null)
                    {
                        m_handshakeOperation.Fault(StatusCodes.BadTimeout);
                        m_handshakeOperation = null;
                    }

                    // close the socket and reconnect.
                    State = TcpChannelState.Closed;

                    if (Socket != null)
                    {
                        Utils.Trace("TCPCLIENTCHANNEL SOCKET CLOSED: {0:X8}, ChannelId={1}", Socket.Handle, ChannelId);
                        Socket.Close();
                        Socket = null;
                    }
                    
                    // create an operation.
                    m_handshakeOperation = BeginOperation(Int32.MaxValue, m_HandshakeComplete, null);

                    State = TcpChannelState.Connecting;
                    Socket = new TcpMessageSocket(this, BufferManager, Quotas.MaxBufferSize);
                    Socket.BeginConnect(m_via, m_ConnectCallback, m_handshakeOperation);
                }
            }
            catch (Exception e)
            {
                Utils.Trace("Channel {0}: Reconnect Failed {1}.", ChannelId, e.Message);
                ForceReconnect(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error reconnecting or renewing a token."));
            }
        }
All Usage Examples Of Opc.Ua.Bindings.TcpMessageSocket::BeginConnect