private void ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, TimeSpan timeout)
 {
     try
     {
         socket.ConnectAsync(endpoint.HostName, endpoint.Port)
         .TimeoutAfter(timeout)
         .ConfigureAwait(false)
         // this ensures exceptions aren't wrapped in an AggregateException
         .GetAwaiter()
         .GetResult();
     }
     catch (ArgumentException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (SocketException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (NotSupportedException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (TimeoutException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
 }
示例#2
0
        /// <summary>
        /// Opens the transport connection with the specified Uri and begins to read from the stream.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override async Task PerformOpenAsync(Uri uri, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!_tcpClient.Connected)
            {
                if (uri == null)
                {
                    throw new ArgumentNullException(nameof(uri), "The uri is mandatory for a not connected TCP client");
                }
                if (uri.Scheme != UriSchemeNetTcp)
                {
                    throw new ArgumentException($"Invalid URI scheme. Expected is '{UriSchemeNetTcp}'.", nameof(uri));
                }

                if (string.IsNullOrWhiteSpace(_hostName))
                {
                    _hostName = uri.Host;
                }

                await _tcpClient.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false);
            }

            _stream = _tcpClient.GetStream();
        }
示例#3
0
        /// <summary>
        /// Opens the transport connection with
        /// the specified Uri and begins to
        /// read from the stream
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public async override Task OpenAsync(Uri uri, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!_tcpClient.Connected)
            {
                if (uri == null)
                {
                    throw new ArgumentNullException("uri");
                }

                if (uri.Scheme != Uri.UriSchemeNetTcp)
                {
                    throw new ArgumentException(string.Format("Invalid URI scheme. Expected is '{0}'.", Uri.UriSchemeNetTcp));
                }

                if (string.IsNullOrWhiteSpace(_hostName))
                {
                    _hostName = uri.Host;
                }

                await _tcpClient.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false);
            }

            _stream = _tcpClient.GetStream();
        }
示例#4
0
        /// <summary>
        /// Opens the transport connection with the specified Uri and begins to read from the stream.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override async Task PerformOpenAsync(Uri uri, CancellationToken cancellationToken)
        {
            // TODO: It is required to call OpenAsync in a server transport, which doesn't make much sense. The server transport is passive and it will be always be open after its creation.
            // We should refactor the transports to remove this need on the server side.
            if (!_tcpClient.Connected)
            {
                if (uri == null)
                {
                    throw new ArgumentNullException(nameof(uri), "The uri is mandatory for a not connected TCP client");
                }
                if (uri.Scheme != UriSchemeNetTcp)
                {
                    throw new ArgumentException($"Invalid URI scheme. Expected is '{UriSchemeNetTcp}'.", nameof(uri));
                }

                if (string.IsNullOrWhiteSpace(_hostName))
                {
                    _hostName = uri.Host;
                }

                await _tcpClient.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false);
            }

            _stream = _tcpClient.GetStream();
            await _envelopePipe.StartAsync(cancellationToken);
        }
        public async Task SendAsync(IRequest request)
        {
            if (!_tcpClient.Connected)
            {
                await _tcpClient.ConnectAsync(IPAddress.Parse(_userSettings.GetString("ServerIP")), _userSettings.GetInt32("ServerPort"));
            }

            if (request is IConnectionRequiredRequest connectionRequiredRequest)
            {
                connectionRequiredRequest.ConnectionIdentifier0 = _connectionIdentification.Current[0];
                connectionRequiredRequest.ConnectionIdentifier1 = _connectionIdentification.Current[1];
                connectionRequiredRequest.ConnectionIdentifier2 = _connectionIdentification.Current[2];
                connectionRequiredRequest.ConnectionIdentifier3 = _connectionIdentification.Current[3];
            }

            request.Counter = ++_counter;
            await _tcpClient.WriteAsync(_requestBuilder.Build(request));

            var dataBytes = await _tcpClient.ReadAsync();

            var response = _responseParser.Parse(dataBytes);

            if (response.IsNotConnectedResponse())
            {
                await SendAsync(new ConnectDataRequest());
                await SendAsync(request);
            }

            ReceiveData?.Invoke(response);
        }
示例#6
0
        private async Task <IReadOnlyList <IMailReference> > TrySendToMx(
            string target,
            IReadOnlyList <IMailReference> mails,
            int port,
            CancellationToken token)
        {
            _log.Verbose($"Looking up information for MX {target}");
            IPAddress targetIp = await _dns.QueryIp(target, token);

            if (targetIp == null)
            {
                _log.Warning($"Failed to resolve A or AAAA record for MX record {target}");
                return(mails);
            }

            using (ITcpClient mxClient = _tcp.GetClient())
            {
                _log.Information($"Connecting to MX {target} at {targetIp} on port {port}");
                await mxClient.ConnectAsync(targetIp, port);

                using (Stream mxStream = mxClient.GetStream())
                {
                    mails = await TrySendMailsToStream(target, mails, mxStream, token);
                }
            }

            return(mails);
        }
示例#7
0
        private async Task ConnectAsyncImpl(IPAddress ipAddress, int port)
        {
            try
            {
                Disconnecting = false;
                _tcpClient    = _getTcpClient();
                OnConnecting(_tcpClient);
                await _tcpClient.ConnectAsync(ipAddress, port).ConfigureAwait(false);

                OnConnected(_tcpClient);
                await TcpReceiver.ReceiveAsync(_tcpClient).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                throw new TcpIpClientConnectFailedException(exception);
            }
        }
        public async Task <EnvironmentResponse> ConnectAsync(IClient client, ITcpClient tcpClient, Configuration configuration)
        {
            await this.semaphore.WaitAsync();

            try
            {
                await tcpClient.ConnectAsync(configuration.Hostname, configuration.Port);

                using (var session = this.sessionFactory.Create(client))
                {
                    return(await this.startRequestWriter.WriteStartAsync(session, configuration.Mode, configuration.Secret));
                }
            }
            finally
            {
                this.semaphore.Release();
            }
        }
        public async Task Start(string ip, int port)
        {
            if (State != WorkState.NotStarted && State != WorkState.Stopped)
            {
                State = WorkState.Errored;
                await Task.WhenAll(receiver.Stop(), sender.Stop());

                throw new AdminPortException("This Client is working atm. Please Stop it before starting it again.");
            }
            this.ip   = ip;
            this.port = port;

            await tcpClient.ConnectAsync(ip, port);

            await Task.WhenAll(
                sender.Start(tcpClient.GetStream()),
                receiver.Start(tcpClient.GetStream()));

            State = WorkState.Working;
        }
示例#10
0
        public async Task OpenConnectionAsync(IDeviceClient deviceClient, IClientWebSocket clientWebSocket, ITcpClient tcpClient, CancellationTokenSource cancellationTokenSource)
        {
            DeviceStreamRequest streamRequest = await deviceClient.WaitForDeviceStreamRequestAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            if (streamRequest != null)
            {
                await deviceClient.AcceptDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);

                Console.WriteLine($"Device stream accepted from IoT Hub, at {DateTime.UtcNow}");

                clientWebSocket.Options.SetRequestHeader("Authorization", $"Bearer {streamRequest.AuthorizationToken}");

                await clientWebSocket.ConnectAsync(streamRequest.Url, cancellationTokenSource.Token).ConfigureAwait(false);

                Console.WriteLine($"Device stream connected to IoT Hub, at {DateTime.UtcNow}");

                await tcpClient.ConnectAsync(this.HostName, this.Port).ConfigureAwait(false);

                Console.WriteLine($"Device stream connected to local endpoint, at {DateTime.UtcNow}");

                using (var localStream = tcpClient.GetStream())
                {
                    await Task.WhenAny(
                        this.HandleIncomingDataAsync(clientWebSocket, localStream, cancellationTokenSource.Token),
                        this.HandleOutgoingDataAsync(clientWebSocket, localStream, cancellationTokenSource.Token)
                        ).ConfigureAwait(false);

                    localStream.Close();
                    Console.WriteLine($"Device stream closed to local endpoint, at {DateTime.UtcNow}");
                }

                await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationTokenSource.Token).ConfigureAwait(false);
            }
            else
            {
                await deviceClient.RejectDeviceStreamRequestAsync(streamRequest, cancellationTokenSource.Token).ConfigureAwait(false);
            }
        }
示例#11
0
 public Task ConnectAsync(IPAddress parse, int port)
 {
     return(_client.ConnectAsync(parse, port));
 }
 private void Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, int timeout)
 {
     try
     {
         socket.ConnectAsync(endpoint.HostName, endpoint.Port)
                     .TimeoutAfter(timeout)
                     .ConfigureAwait(false)
                     .GetAwaiter()//this ensures exceptions aren't wrapped in an AggregateException
                     .GetResult();
     }
     catch (ArgumentException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (SocketException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (NotSupportedException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
     catch (TimeoutException e)
     {
         throw new ConnectFailureException("Connection failed", e);
     }
 }
示例#13
0
        protected override async Task Run(CancellationToken cancellationToken)
        {
            ITcpClient client = null;

            try
            {
                if (!_messageService.CanSend(_userId, typeof(TMessage)))
                {
                    throw new SecurityAccessDeniedException(string.Format("Access denied for type message {0}", typeof(TMessage)));
                }
                client = _clientFactory.CreateTcpClient();
                await client.ConnectAsync(_userId);

                var definition = _messageService.GetDefinition <TMessage>();
                var buffer     = BitConverter.GetBytes(_messageService.CreateMessageHash(definition));
                await client.WriteStream.WriteAsync(buffer, 0, buffer.Length, cancellationToken);

                await client.WriteStream.FlushAsync(cancellationToken);

                if (!await GetResponse(client.ReadStream, cancellationToken))
                {
                    return;
                }
                if (IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }
                using (var memoryBuffer = new MemoryStream())
                {
                    await _serializer.WriteMessage(_message, memoryBuffer);
                    await Send(cancellationToken, client.WriteStream, memoryBuffer.ToArray());
                }

                if (IsCancellationRequested)
                {
                    throw new OperationCanceledException();
                }

                await client.WriteStream.FlushAsync(cancellationToken);

                if (!await GetResponse(client.ReadStream, cancellationToken))
                {
                    return;
                }

                //TODO: Check variable streaming for correct implementation!
                var streaming = Message as IStreamingMessage;
                if (streaming != null)
                {
                    var   readedCount = 0;
                    ulong readed      = 0;
                    RaiseReport(new ProgressInfo <TMessage>(_message, streaming.StreamLength, readed));
                    buffer = new byte[2048];
                    do
                    {
                        readedCount = await streaming.Stream.ReadAsync(buffer, 0, buffer.Length);

                        await client.WriteStream.WriteAsync(buffer, 0, readedCount, cancellationToken);

                        await client.WriteStream.FlushAsync(cancellationToken);

                        if (IsCancellationRequested)
                        {
                            throw new OperationCanceledException();
                        }
                        readed += (ulong)readedCount;
                        RaiseReport(new ProgressInfo <TMessage>(_message, streaming.StreamLength, readed));
                    } while (readedCount > 0);
                }
                RaiseSuccess(Message);
                await client.DisconnectAsync();
            }
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }
        }