ConnectAsync() public method

public ConnectAsync ( IPAddress address, int port ) : System.Threading.Tasks.Task
address IPAddress
port int
return System.Threading.Tasks.Task
Example #1
1
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting...");
            X509Certificate2 serverCertificate = new X509Certificate2("certificate.pfx"); // Any valid certificate with private key will work fine.
            TcpListener listener = new TcpListener(IPAddress.Any, 4567);
            TcpClient client = new TcpClient();
            listener.Start();

            Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, 4567);
            Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();
            Task.WaitAll(clientConnectTask, listenerAcceptTask);

            TcpClient server = listenerAcceptTask.Result;
            SslStream clientStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption);
            SslStream serverStream = new SslStream(server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption);

            Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false);
            Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(serverCertificate, false, SslProtocols.Tls12, false);
            Task.WaitAll(clientAuthenticationTask, serverAuthenticationTask);
            
            byte[] readBuffer = new byte[256];
            Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); // Create a pending ReadAsync, which will wait for data that will never come (for testing purposes).
            byte[] writeBuffer = new byte[256];
            Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); // The main thread actually blocks here (not asychronously waits) on .NET Core making this call.
            bool result = Task.WaitAll(new Task[1] { writeTask }, 5000); // This code won't even be reached on .NET Core. Works fine on .NET Framework.

            if (result)
            {
                Console.WriteLine("WriteAsync completed successfully while ReadAsync was pending... nothing locked up.");
            }
            else
            {
                Console.WriteLine("WriteAsync failed to complete after 5 seconds.");
            }
        }
Example #2
0
 public static async Task<Socket> ConnectToServerAsync(IPEndPoint endpoint, IEnumerable<AddressFamily> addressFamilies)
 {
     ValidateEndpoint(endpoint, addressFamilies);
     var tcpClient = new TcpClient();
     await tcpClient.ConnectAsync(endpoint.Address, endpoint.Port);
     return tcpClient.Client;
 }
        public async Task ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption()
        {
            using (var serverNoEncryption = new DummyTcpServer(
                new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption))
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port);

                using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
                {
                    if (SupportsNullEncryption)
                    {
                        await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false);
                        _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
                            serverNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);

                        CipherAlgorithmType expected = CipherAlgorithmType.Null;
                        Assert.Equal(expected, sslStream.CipherAlgorithm);
                        Assert.Equal(0, sslStream.CipherStrength);
                    }
                    else
                    {
                        var ae = await Assert.ThrowsAsync<AuthenticationException>(() => sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false));
                        Assert.IsType<PlatformNotSupportedException>(ae.InnerException);
                    }
                }
            }
        }
Example #4
0
        private async Task StartClientToServerComms()
        {
            string host = "10.1.1.84";
            int port = 58846;
            Console.WriteLine("[Relay] Connecting to {0}:{1}", host, port);

            using (var nextTcpClient = new TcpClient())
            {
                await nextTcpClient.ConnectAsync(host, port);
                Console.WriteLine("[Relay] Connected to server");
                byte[] clientBuffer = new byte[4096];
                using (var clientToServerNetworkStream = new SslStream(nextTcpClient.GetStream(), true,
                    (sender, certificate, chain, errors) => { return true; }))
                {

                    clientToServerNetworkStream.AuthenticateAsClient(host);
                    while (true)
                    {
                        var clientBytes = await clientToServerNetworkStream.ReadAsync(clientBuffer, 0, clientBuffer.Length);

                        if (clientBytes > 0)
                        {
                            Console.WriteLine("Client sent {0}", DelugeRPC.DelugeProtocol.DecompressAndDecode(clientBuffer).Dump());
                            await clientToServerNetworkStream.WriteAsync(clientBuffer, 0, clientBuffer.Length);
                        }
                    }
                }
            }
        }
Example #5
0
        private static async Task<int> Run(int port) {
            using (var client = new TcpClient()) {
                await client.ConnectAsync(IPAddress.Loopback, port);

                var utf8 = new UTF8Encoding(false);
                using (var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true))
                using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                    var filename = await reader.ReadLineAsync();
                    var args = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => utf8.GetString(Convert.FromBase64String(s)))
                        .ToList();
                    var workingDir = await reader.ReadLineAsync();
                    var env = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => s.Split(new[] { '=' }, 2))
                        .Select(s => new KeyValuePair<string, string>(s[0], utf8.GetString(Convert.FromBase64String(s[1]))))
                        .ToList();
                    var outputEncoding = await reader.ReadLineAsync();
                    var errorEncoding = await reader.ReadLineAsync();

                    return await ProcessOutput.Run(
                        filename,
                        args,
                        workingDir,
                        env,
                        false,
                        new StreamRedirector(writer, outputPrefix: "OUT:", errorPrefix: "ERR:"),
                        quoteArgs: false,
                        elevate: false,
                        outputEncoding: string.IsNullOrEmpty(outputEncoding) ? null : Encoding.GetEncoding(outputEncoding),
                        errorEncoding: string.IsNullOrEmpty(errorEncoding) ? null : Encoding.GetEncoding(errorEncoding)
                    );
                }
            }
        }
Example #6
0
	    public async Task<TcpClient> ConnectAsync(string hostname, int port)
	    {
	        TcpClient client = new TcpClient();
	        await client.ConnectAsync(hostname, port);
	        DoHandshake(client, hostname, port);
	        return client;
	    } 
Example #7
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                TcpClient tcpclnt = new TcpClient();

                label4.Text = "Attempting to connect to RPi...";

                if (tcpclnt.ConnectAsync("192.168.55.3", 5069).Wait(1000))
                {
                    label4.Text = "Couldn't connect to RPi";
                }
                else
                {
                    label4.Text = "Connected to RPi";

                    this.Hide();

                    Form MainForm = new MainForm();
                    MainForm.Show();

                    timer1.Dispose();
                }
            }
            else
            {
                label4.Text = "Waiting for network...";
            }
        }
Example #8
0
        public static void Main(string[] args)
        {
            if(args.Length != 1)
            {
                Console.WriteLine("need ipadress ");
                return;
            }
            IPAddress ipAddress = IPAddress.Parse(args[0]);
            int port = 7681;

            TcpClient client = new TcpClient();
            client.ConnectAsync(ipAddress, port).Wait();
            Console.WriteLine("connected");
            using (NegotiateStream stream = new NegotiateStream(client.GetStream()))
            {
                Console.WriteLine("authenticating");
                stream.AuthenticateAsClientAsync(CredentialCache.DefaultNetworkCredentials, null, "HOST/skapilac10.fareast.corp.microsoft.com").Wait();
                Console.WriteLine("authenticated");
                var sendBuffer = Encoding.UTF8.GetBytes("Request from client");
                stream.Write(sendBuffer, 0, sendBuffer.Length);
                var recvBuffer = new byte[1024];
                var byteCount = stream.Read(recvBuffer, 0, recvBuffer.Length);
                Console.WriteLine("Recieved: {0}", Encoding.UTF8.GetString(recvBuffer, 0, byteCount));
            }
        }
Example #9
0
        public override bool Initialize()
        {
            Logger.Log($"Connecting to Twitch IRC -> {Account.Username}");

            _Client = new TcpClient();
            _Client.ConnectAsync("irc.twitch.tv", 6667).Wait();

            _Writer = new StreamWriter(_Client.GetStream());
            _Reader = new StreamReader(_Client.GetStream());

            Logger.Log("Sending login credentials");

            _SendStringRaw($"PASS {Account.OAuth}");
            _SendStringRaw($"NICK {Account.Username}");

            var response = IRCMessage.Parse(_Reader.ReadLine());
            if (response.Type != "001")
            {
                Logger.Log("Server did not return expected login message");
                return false;
            }

            // runners
            new Thread(_SendRunner).Start();
            new Thread(_ReceiveRunner).Start();

            Logger.Log("Connecting to channels");
            foreach (var c in Channels)
                _SendString($"JOIN #{c}", MessagePriority.Medium);

            return true;
        }
Example #10
0
        /// <summary>
        /// Method to determine if the user's clock is syncrhonised to NIST time.
        /// </summary>
        private static async Task BeginCheckAsync()
        {
            if (!NetworkMonitor.IsNetworkAvailable)
            {
                // Reschedule later otherwise
                ScheduleCheck(TimeSpan.FromMinutes(1));
                return;
            }

            EveMonClient.Trace();

            Uri url = new Uri(NetworkConstants.NISTTimeServer);
            DateTime serverTimeToLocalTime;
            bool isSynchronised;

            await Dns.GetHostAddressesAsync(url.Host)
                .ContinueWith(async task =>
                {
                    IPAddress[] ipAddresses = task.Result;

                    if (!ipAddresses.Any())
                        return;

                    try
                    {
                        DateTime dateTimeNowUtc;
                        DateTime localTime = DateTime.Now;
                        using (TcpClient tcpClient = new TcpClient())
                        {
                            await tcpClient.ConnectAsync(ipAddresses.First(), url.Port);

                            using (NetworkStream netStream = tcpClient.GetStream())
                            {
                                // Set a three seconds timeout
                                netStream.ReadTimeout = (int)TimeSpan.FromSeconds(3).TotalMilliseconds;

                                byte[] data = new byte[24];
                                await netStream.ReadAsync(data, 0, data.Length);
                                data = data.Skip(7).Take(17).ToArray();
                                string dateTimeText = Encoding.ASCII.GetString(data);
                                dateTimeNowUtc = DateTime.ParseExact(dateTimeText,
                                    "yy-MM-dd HH:mm:ss",
                                    CultureInfo.CurrentCulture.DateTimeFormat,
                                    DateTimeStyles.AssumeUniversal);
                            }
                        }

                        serverTimeToLocalTime = dateTimeNowUtc.ToLocalTime();
                        TimeSpan timediff =
                            TimeSpan.FromSeconds(Math.Abs(serverTimeToLocalTime.Subtract(localTime).TotalSeconds));
                        isSynchronised = timediff < TimeSpan.FromSeconds(60);

                        OnCheckCompleted(isSynchronised, serverTimeToLocalTime, localTime);
                    }
                    catch (Exception exc)
                    {
                        CheckFailure(exc);
                    }
                }, EveMonClient.CurrentSynchronizationContext).ConfigureAwait(false);
        }
Example #11
0
		/// <summary>
		/// Connects the client to a remote host using the specified 
		/// IP address and port number as an asynchronous operation.
		/// </summary>
		/// <param name="host">host.</param>
		/// <param name="port">port.</param>
		/// <param name="certificate">certificate.</param>
		/// <exception cref="ConnectionInterruptedException"></exception>
		public async Task ConnectAsync(string host, int port, X509Certificate2 certificate)
		{
			try
			{
				// connect via tcp
				tcpClient = new TcpClient();
				await tcpClient.ConnectAsync(host, port);

				await Task.Run(() =>
				{
					// create ssl stream
					sslStream = new SslStream(tcpClient.GetStream(), true,
						Ssl.ServerValidationCallback,
						Ssl.ClientCertificateSelectionCallback,
						EncryptionPolicy.RequireEncryption);

					// handshake
					Ssl.ClientSideHandshake(certificate, sslStream, host);
				});
			}
			catch (CertificateException e)
			{
				throw new ConnectionInterruptedException("Connection failed. Reason: " + e.Message);
			}
			catch
			{
				throw new ConnectionInterruptedException("Connection failed.");
			}
		}
Example #12
0
        public async Task<bool> Connect(string hostname, int port)
        {
            if(ServerConnectionStarting != null)
                ServerConnectionStarting(this, new ServerConnectionEventArgs{Message = "Connecting to " + hostname + ":" + port.ToString() + "...", Status = ServerConnectionStatus.Connecting, Timestamp = DateTime.Now});

            try
            {
                TcpClient = new TcpClient();
                TcpClient.NoDelay = true;
                await TcpClient.ConnectAsync(hostname, port);
            }
            catch
            {
                if(ServerConnectionFailed != null)
                    ServerConnectionFailed(this, new ServerConnectionEventArgs{Message = "Failed to connect!  Make sure the server is running and that your hostname and port are correct.", Status = ServerConnectionStatus.Disconnected, Timestamp = DateTime.Now});
            }
            if(IsConnected)
            {
                TcpClientStream = TcpClient.GetStream();

                if(ServerConnectionSucceeded != null)
                    ServerConnectionSucceeded(this, new ServerConnectionEventArgs{Message = "Successfully connected.", Status = ServerConnectionStatus.Connected, Timestamp = DateTime.Now});

                Keepalive.Reset();
                return true;
            }
            else return false;
        }
        public void Download()
        {
            using (TcpClient tcpClient = new TcpClient())
            {
                if (!tcpClient.ConnectAsync(IpAdress, 80).Wait(TIMEOUT))
                {
                    Console.WriteLine("La connection vers " + Uri + " a timeout");
                    return;
                }
                stream = tcpClient.GetStream();

                var byteRequest = Encoding.ASCII.GetBytes(string.Format(GetRequest, Uri.LocalPath, Uri.Host));
                stream.Write(byteRequest, 0, byteRequest.Length);
                bufferSize = tcpClient.ReceiveBufferSize;

                List<byte> srcByte = new List<byte>();
                while (!stream.DataAvailable) ;
                while (stream.DataAvailable)
                {
                    byte[] data = new byte[bufferSize];
                    int read = stream.Read(data, 0, bufferSize);
                    srcByte.AddRange(data.Take(read));
                }

                ParseRequest(srcByte.ToArray());
            }
        }
Example #14
0
        private async Task SendServiceMessage(Message packet)
        {
            var command = packet.Json;
            try
            {
                using (var tcpClient = new TcpClient())
                {
                    await tcpClient.ConnectAsync(IPAddress.Loopback, 22005);
                    using (var stream = tcpClient.GetStream())
                    using (var sw = new StreamWriter(stream, Encoding.UTF8))
                    {

                        if (tcpClient.Connected)
                        {
                            await sw.WriteLineAsync(command);
                            await sw.FlushAsync();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        protected override async Task Send(SyslogMessage syslogMessage)
        {
            var client = new TcpClient();
            client.ConnectAsync(Hostname, LogglyConfig.Instance.Transport.EndpointPort).Wait();

            try
            {
                byte[] messageBytes = syslogMessage.GetBytes();
                var networkStream = await GetNetworkStream(client).ConfigureAwait(false);
                await networkStream.WriteAsync(messageBytes, 0, messageBytes.Length).ConfigureAwait(false);
                await networkStream.FlushAsync().ConfigureAwait(false);
            }
            catch (AuthenticationException e)
            {
                LogglyException.Throw(e, e.Message);
            }
            finally
            {
#if NET_STANDARD
                client.Dispose();
#else
                client.Close();
#endif
            }

        }
 public override Task PostEmailAsync(string name, string[] to, string[] cc, string[] bcc, string subject, string message, params Attachment[] Attachments)
 {
     if (!ssl)
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = client.GetStream())
                 using (var reader = new StreamReader(stream))
                 using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                 {
                     TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                 }
             }
         });
     else
         return Task.Factory.StartNew(async () =>
         {
             using (var client = new TcpClient())
             {
                 await client.ConnectAsync(server, port);
                 using (var stream = new SslStream(client.GetStream(), false))
                 {
                     await stream.AuthenticateAsClientAsync(server);
                     using (var reader = new StreamReader(stream))
                     using (var writer = new StreamWriter(stream) { AutoFlush = true, NewLine = "\r\n" })
                     {
                         TcpWrite(writer, reader, name, to, cc, bcc, subject, message, Attachments);
                     }
                 }
             }
         });
 }
        public static async Task SendAndReceive()
        {
            using (var client = new TcpClient())
            {
                await client.ConnectAsync(host, port);
                using (NetworkStream stream = client.GetStream())
                using (var writer = new StreamWriter(stream, Encoding.ASCII, 1024, leaveOpen: true))
                using (var reader = new StreamReader(stream, Encoding.ASCII, true, 1024, leaveOpen: true))
                {
                    writer.AutoFlush = true;
                    string line = string.Empty;
                    do
                    {
                        WriteLine("enter a string, bye to exit");
                        line = ReadLine();
                        await writer.WriteLineAsync(line);
                       
                        string result = await reader.ReadLineAsync();
                        WriteLine($"received {result} from server");
                    } while (line != "bye");

                    WriteLine("so long, and thanks for all the fish");

                }
            }
            
        }
        public async Task ReadLineAsync_ThrowsOnConnectionClose()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);

            try
            {
                listener.Start();
                Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync();

                TcpClient client = new TcpClient();
                await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using (TcpClient serverTcpClient = await acceptTask)
                {
                    TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient);
                    client.Dispose();

                    await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () =>
                    {
                        await channel.ReadLineAsync();
                    });
                }
            }
            finally
            {
                listener.Stop();
            }
        }
Example #19
0
 public async Task ConnectAsync(string hostname, int port)
 {
     _tcpClient = new TcpClient();
     await _tcpClient.ConnectAsync(hostname, port);
     var networkStream = _tcpClient.GetStream();
     _reader = new StreamReader(networkStream, Encoding.ASCII, false, BufferSize, true);
     _writer = new StreamWriter(networkStream, Encoding.ASCII, BufferSize, true);
 }
        public async Task<DebugSession> ConnectToServerAsync(string ipAddress)
        {
            CurrentServer = IPAddress.Parse(ipAddress);

            var tcp = new TcpClient();
            await tcp.ConnectAsync(CurrentServer, MonoDebugServer.TcpPort);
            return new DebugSession(this, _type, tcp.Client);
        }
 private static async Task ConsumeOneAsync(TcpClient client, IPAddress ip, int port)
 {
     await client.ConnectAsync(ip, port);
     using (var stream = client.GetStream())
     {
         await TcpMessenger.ReadAndWriteAsync(stream, Constants.ServerToClient, Constants.ClientToServer);
     }
 }
 protected override async Task<Stream> ConnectForShutdownAsync(string pipeName, int timeout)
 {
     var port = int.Parse(pipeName);
     var ipAddress = IPAddress.Parse(DefaultAddress);
     var client = new TcpClient();
     await client.ConnectAsync(ipAddress, port).ConfigureAwait(false);
     return client.GetStream();
 }
Example #23
0
        public async Task<PingPayload> Ping(){

            NetworkStream = null;
            WriteBuffer.Clear();
            ReadOffset = 0;
            var client = new TcpClient();

            await client.ConnectAsync(Host, Port);
            if (!client.Connected)
                return null;
            
            NetworkStream = client.GetStream();


            /*
             * Send a "Handshake" packet
             * http://wiki.vg/Server_List_Ping#Ping_Process
             */
            WriteVarInt(47);
            WriteString(Host);
            WriteShort(Port);
            WriteVarInt(1);
            await Flush(0);

            /*
             * Send a "Status Request" packet
             * http://wiki.vg/Server_List_Ping#Ping_Process
             */
            await Flush(0);



            var message = new List<byte>();
            var buf = new byte[1024];
            var bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
            message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
            var length = ReadVarInt(buf);
            var left = length - (message.Count - ReadOffset);
            while (left > 0) {
                buf = new byte[1024]; 
                bytes = await NetworkStream.ReadAsync(buf, 0, buf.Length, CancellationToken);
                message.AddRange(new ArraySegment<byte>(buf, 0, bytes));
                left -= bytes;
            }

            client.Close();

            ReadOffset = 0;
            var buffer = message.ToArray();
            length = ReadVarInt(buffer);
            ReadVarInt(buffer); // packetID
            var jsonLength = ReadVarInt(buffer);
            var json = ReadString(buffer, jsonLength);
            var ping = JsonConvert.DeserializeObject<PingPayload>(json);
            ping.Motd = ping.Motd != null ? CleanMotd(ping.Motd) : null;

            return ping;
        }
Example #24
0
        public async Task Connect ()
        {
            if (IsConnected ())
                return;

            tcp = new TcpClient ();

            // Disable Nagle for HTTP/2
            tcp.NoDelay = true;

            await tcp.ConnectAsync (Host, (int)Port);

            if (UseTls) {
                sslStream = new SslStream (tcp.GetStream (), false, 
                    (sender, certificate, chain, sslPolicyErrors) => true);
                
                await sslStream.AuthenticateAsClientAsync (
                    Host, 
                    Certificates ?? new X509CertificateCollection (), 
                    System.Security.Authentication.SslProtocols.Tls12, 
                    false);

                clientStream = sslStream;
            } else {
                clientStream = tcp.GetStream ();
            }

            // Send out preface data
            var prefaceData = System.Text.Encoding.ASCII.GetBytes (ConnectionPreface);
            await clientStream.WriteAsync (prefaceData, 0, prefaceData.Length);
            await clientStream.FlushAsync ();
            
            // Start reading the stream on another thread
            var readTask = Task.Factory.StartNew (() => {
                try { read (); }
                catch (Exception ex) {
                    Console.WriteLine ("Read error: " + ex);
                    Disconnect ();
                }
            }, TaskCreationOptions.LongRunning);

            readTask.ContinueWith (t => {
                // TODO: Handle the error
                Console.WriteLine ("Error: " + t.Exception);
                Disconnect ();
            }, TaskContinuationOptions.OnlyOnFaulted);

            // Send an un-ACK'd settings frame
            await SendFrame(new SettingsFrame ());

            // We need to wait for settings server preface to come back now
            resetEventConnectionSettingsFrame = new ManualResetEventSlim ();
            resetEventConnectionSettingsFrame.Reset ();
            if (!resetEventConnectionSettingsFrame.Wait (ConnectionTimeout)) {
                Disconnect ();
                throw new Exception ("Connection timed out");
            }
        }
Example #25
0
        private static async void ConnectAsTcpClient()
        {
            using (var tcpClient = new TcpClient())
            {

                //todo: https://github.com/fuzeman/rencode-sharp/issues/6
                string host = "10.1.1.104";
                int port = 58846;
                Console.WriteLine("[Client] Connecting to server");

                await tcpClient.ConnectAsync(host, port);
                Console.WriteLine("[Client] Connected to server");
                using (var networkStream = new SslStream(tcpClient.GetStream(), true,
                    (sender, certificate, chain, errors) => { return true; }))
                {

                    networkStream.AuthenticateAsClient(host);
                    Commands command = new Commands(networkStream);
                    command.OnLogin += (o, e) => { Console.WriteLine("logged in"); };
                    command.OnError += (o, e) =>
                    {
                        HandleError(((RPCErrorEventArgs)e).Message);
                    };
                    command.Login("localclient", "test");

                    //while (!command.IsLoggedIn)
                    //{
                    //    Thread.Sleep(1000);
                    //}

                    //command.Info();
                    //command.GetFilterTree();
                    //command.GetSessionStatus();
                    //command.GetFilterTree();
                    //command.GetFreeSpace();
                    //command.GetNumConnections();
                    //command.GetConfigValuesDefault();
                    command.AddTorrent("magnet:?xt=urn:btih:3f19b149f53a50e14fc0b79926a391896eabab6f&dn=ubuntu-15.10-desktop-amd64.iso");


                    while (true)
                    {
                        var buffer = new byte[4096];
                        var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                        var response = DelugeProtocol.DecompressAndDecode(buffer) as object[];

                        if (response != null)
                        {
                            command.HandleResponse(response);
                        }

                    }
                    

                }
            }
        }
Example #26
0
        protected override async Task<BuildResponse> RunServerCompilation(List<string> arguments, BuildPaths buildPaths, string keepAlive, string libDirectory, CancellationToken cancellationToken)
        {
            var client = new TcpClient();
            await client.ConnectAsync("127.0.0.1", port: 12000).ConfigureAwait(true);

            var request = BuildRequest.Create(_language, buildPaths.WorkingDirectory, arguments, keepAlive, libDirectory);
            await request.WriteAsync(client.GetStream(), cancellationToken).ConfigureAwait(true);
            return await BuildResponse.ReadAsync(client.GetStream(), cancellationToken).ConfigureAwait(true);
        }
Example #27
0
		public async Task<byte[]> ConnectAsync() {
			client = new TcpClient ();
			await client.ConnectAsync (IPAddress.Loopback, 1984);
			var stream = client.GetStream ();
			await stream.WriteAsync (new byte[] { 1, 9, 8, 4 }, 0, 4);
			var buffer = new byte[8];
			await stream.ReadAsync (buffer, 0, 8);
			return buffer;
		}
        public async void SslStream_SendReceiveOverNetworkStream_Ok()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 0);

            using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate())
            using (TcpClient client = new TcpClient())
            {
                listener.Start();

                Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
                Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync();

                await Task.WhenAll(clientConnectTask, listenerAcceptTask);

                TcpClient server = listenerAcceptTask.Result;
                using (SslStream clientStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null,
                    EncryptionPolicy.RequireEncryption))
                using (SslStream serverStream = new SslStream(
                    server.GetStream(),
                    false,
                    null,
                    null,
                    EncryptionPolicy.RequireEncryption))
                {

                    Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync(
                        serverCertificate.GetNameInfo(X509NameType.SimpleName, false),
                        null,
                        SslProtocols.Tls12,
                        false);

                    Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync(
                        serverCertificate,
                        false,
                        SslProtocols.Tls12,
                        false);

                    await Task.WhenAll(clientAuthenticationTask, serverAuthenticationTask);

                    byte[] readBuffer = new byte[256];
                    Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length);

                    byte[] writeBuffer = new byte[256];
                    Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length);

                    bool result = Task.WaitAll(
                        new Task[1] { writeTask }, 
                        TestConfiguration.PassingTestTimeoutMilliseconds);

                    Assert.True(result, "WriteAsync timed-out.");
                }
            }
        }
 public async Task ConnectAsync()
 {
     IsConnected = false;
     _triedConnect = true;
     _tcpClient = new TcpClient();
     await _tcpClient.ConnectAsync(GlobalConfig.IpAddress, GlobalConfig.Port).ConfigureAwait(false);
     StartListening();
     IsConnected = true;
 }
Example #30
0
 public async Task ConnectAsync()
 {
     IsConnecting = true;
     _tcpClient = new TcpClient();
     await _tcpClient.ConnectAsync(GlobalConfig.IpAddress, GlobalConfig.Port);
     _networkStream = _tcpClient.GetStream();
     IsConnecting = false;
     Task.Run(() => StartListening());
 }