当前位置: 首页>>代码示例>>C#>>正文


C# SslStream.ReadAsync方法代码示例

本文整理汇总了C#中System.Net.Security.SslStream.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# SslStream.ReadAsync方法的具体用法?C# SslStream.ReadAsync怎么用?C# SslStream.ReadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Security.SslStream的用法示例。


在下文中一共展示了SslStream.ReadAsync方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        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.");
            }
        }
开发者ID:xanather,项目名称:SslStreamTest,代码行数:35,代码来源:Program.cs

示例2: StartClientToServerComms

        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);
                        }
                    }
                }
            }
        }
开发者ID:voltagex,项目名称:junkcode,代码行数:29,代码来源:Program.cs

示例3: ConnectAsTcpClient

        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);
                        }

                    }
                    

                }
            }
        }
开发者ID:voltagex,项目名称:junkcode,代码行数:57,代码来源:Program.cs

示例4: Accept

        public override async void Accept()
        {
            try
            {
                if (Sockets[0].AcceptSocket != null)
                {
                    networkStream = new NetworkStream(Sockets[0].AcceptSocket);
                    tlsStream = new SslStream(networkStream, false);
                    tlsSemaphore = new SemaphoreSlim(1, 1);

                    await tlsStream.AuthenticateAsServerAsync(Manager.Session.Certificate, false, SslProtocols.Tls12, false);

                    if (tlsStream.IsAuthenticated && Manager.Session.Add(this))
                    {
                        var buffer = Sockets[0].Buffer;
                        int numReadBytes;

                        do
                        {
                            numReadBytes = await tlsStream.ReadAsync(buffer, 0, buffer.Length);

                            if (numReadBytes == 0)
                                break;

                            var headerLength = (buffer[0] << 8) | buffer[1];
                            var header = Header.Parser.ParseFrom(new CodedInputStream(buffer, 2, headerLength));
                            var data = new byte[header.Size];

                            if (header.Size > 0)
                                Buffer.BlockCopy(buffer, 2 + headerLength, data, 0, data.Length);

                            await Manager.BnetPacket.CallHandler(header, data, this);
                        } while (numReadBytes != 0);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Message(LogTypes.Error, ex.Message);
            }
            finally
            {
                if (Manager.Session.Remove(this))
                    Dispose();
            }
        }
开发者ID:Arctium-Emulation,项目名称:Project-WoW,代码行数:46,代码来源:BnetSession.cs

示例5: HandleConnectionAsync

        // Handle new connection
        private async Task HandleConnectionAsync(TcpClient tcpClient)
        {
            await Task.Yield();
            // continue asynchronously on another threads

            using (var networkStream = new SslStream(tcpClient.GetStream()))
            {
                var configItems = new object[]
                {
                    new object[] {"listen_ports", new object[] {"31337", "1337"}},
                    new object[] {"dht", true},
                    new object[] {"info_sent", 0.0},
                    new object[] {"lsd", true},
                    new object[] {"max_download_speed", -1.0},
                    new object[] {"send_info", false},
                    new object[] {"natpmp", true},
                    new object[] {"move_completed_path", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"peer_tos", "0x00"},
                    new object[] {"enc_in_policy", 1},
                    new object[] {"queue_new_to_top", false},
                    new object[] {"ignore_limits_on_local_network", true},
                    new object[] {"rate_limit_ip_overhead", true},
                    new object[] {"daemon_port", 58846},
                    new object[] {"torrentfiles_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"max_active_limit", 8},
                    new object[] {"geoip_db_location", "/usr/share/GeoIP/GeoIP.dat"},
                    new object[] {"upnp", true},
                    new object[] {"utpex", true},
                    new object[] {"max_active_downloading", 3},
                    new object[] {"max_active_seeding", 5},
                    new object[] {"allow_remote", true},
                    new object[] {"enabled_plugins", new object[0]},
                    new object[] {"max_half_open_connections", 8},
                    new object[] {"download_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"compact_allocation", false},
                    new object[] {"max_upload_speed", -1.0},
                    new object[] {"plugins_location", "C:\\Users\\Adam\\AppData\\Roaming\\deluge\\plugins"},
                    new object[] {"max_connections_global", 200},
                    new object[] {"enc_prefer_rc4", true},
                    new object[] {"cache_expiry", 60},
                    new object[] {"stop_seed_at_ratio", false},
                    new object[] {"stop_seed_ratio", 2.0},
                    new object[] {"max_download_speed_per_torrent", -1},
                    new object[] {"prioritize_first_last_pieces", false},
                    new object[] {"max_upload_speed_per_torrent", -1},
                    new object[] {"auto_managed", true},
                    new object[] {"enc_level", 2},
                    new object[] {"copy_torrent_file", false},
                    new object[] {"max_connections_per_second", 20},
                    new object[] {"dont_count_slow_torrents", false},
                    new object[] {"add_paused", false},
                    new object[] {"random_outgoing_ports", true},
                    new object[] {"max_upload_slots_per_torrent", -1},
                    new object[] {"new_release_check", true},
                    new object[] {"enc_out_policy", 1},
                    new object[] {"seed_time_ratio_limit", 7.0},
                    new object[] {"remove_seed_at_ratio", false},
                    new object[] {"autoadd_location", "C:\\Users\\Adam\\Downloads"},
                    new object[] {"max_upload_slots_global", 4},
                    new object[] {"seed_time_limit", 180},
                    new object[] {"cache_size", 512},
                    new object[] {"share_ratio_limit", 2.0},
                    new object[] {"random_port", true},
                    new object[] {"listen_interface", ""},
                    new object[] { "max_connections_per_torrent", -1},
                    new object[] {"move_completed", false}

                };

                await networkStream.AuthenticateAsServerAsync(X509Certificate2.CreateFromCertFile(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "deluge.pfx")));
                var buffer = new byte[4096];
                var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                var bufferObject = DelugeRPC.DelugeProtocol.DecompressAndDecode(buffer);
                var id = (((bufferObject) as object[])[0] as object[])[0];
                var response = DelugeRPC.DelugeProtocol.CompressAndEncode(new object[] { 1, id, 10 });
                //var serverResponseBytes = Encoding.UTF8.GetBytes("Hello from server");
                await networkStream.WriteAsync(response, 0, response.Length);
                //Console.WriteLine("[Server] Response has been written");




                while (true)
                {

                    byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);
                    if (byteCount > 0)
                    {
                        var handled = false;
                        var temp = DelugeRPC.DelugeProtocol.DecompressAndDecode(buffer);
                        var tempMessage = new RPCMessage(temp as object[]);
                        Console.WriteLine(tempMessage.ID);
                        if (tempMessage.Command == "daemon.info")
                        {
                            response =
                                DelugeRPC.DelugeProtocol.CompressAndEncode(new object[] {1, tempMessage.ID, "6.6.6"});
                            handled = true;
                            networkStream.WriteAsync(response, 0, response.Length);

//.........这里部分代码省略.........
开发者ID:voltagex,项目名称:junkcode,代码行数:101,代码来源:Program.cs


注:本文中的System.Net.Security.SslStream.ReadAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。