예제 #1
0
        static void Example(int port)
        {
            QuicListener listener = new QuicListener(port);

            listener.Start();

            while (true)
            {
                // Blocks while waiting for a connection
                QuicConnection client = listener.AcceptQuicClient();

                // Assign an action when a data is received from that client.
                client.OnDataReceived += (c) => {
                    byte[]   data         = c.Data;
                    DateTime timeRecieved = DateTime.Now.ToLocalTime();
                    //string message = cleanMessage(data);
                    string message = Encoding.UTF8.GetString(data);

                    Req request = JsonConvert.DeserializeObject <Req>(message);
                    request.timeRecieved    = timeRecieved;
                    request.number_of_bytes = data.Length;
                    //Console.WriteLine("Data received: " + Encoding.UTF8.GetString(data));
                    string aaa   = JsonConvert.SerializeObject(request);
                    byte[] bytes = System.Text.Encoding.UTF8.GetBytes(aaa);//Unicode
                    c.Send(bytes);
                    //c.Send(Encoding.UTF8.GetBytes("Echo!"));
                };
            }
        }
예제 #2
0
        private static void Main()
        {
            var listener = new QuicListener(11000);

            listener.Start();

            while (true)
            {
                // Blocks while waiting for a connection
                var client = listener.AcceptQuicClient();

                // Assign an action when a data is received from that client.
                client.OnDataReceived += c =>
                {
                    var data = c.Data;

                    Console.WriteLine("Data received: " + Encoding.Unicode.GetString(data));

                    c.Send(Encoding.UTF8.GetBytes("Echo!"));
                };
            }

            // ReSharper disable once FunctionNeverReturns
            // We need this so the server actually responds
        }
예제 #3
0
        public async Task SetListenerTimeoutWorksWithSmallTimeout()
        {
            var quicOptions = new QuicListenerOptions();

            quicOptions.IdleTimeout = TimeSpan.FromSeconds(10);
            quicOptions.ServerAuthenticationOptions = GetSslServerAuthenticationOptions();
            quicOptions.ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0);

            using QuicListener listener = new QuicListener(QuicImplementationProviders.MsQuic, quicOptions);
            listener.Start();

            QuicClientConnectionOptions options = new QuicClientConnectionOptions()
            {
                RemoteEndPoint = listener.ListenEndPoint,
                ClientAuthenticationOptions = GetSslClientAuthenticationOptions(),
            };

            using QuicConnection clientConnection = new QuicConnection(QuicImplementationProviders.MsQuic, options);
            ValueTask clientTask = clientConnection.ConnectAsync();

            using QuicConnection serverConnection = await listener.AcceptConnectionAsync();

            await clientTask;

            await Assert.ThrowsAsync <QuicOperationAbortedException>(async() => await serverConnection.AcceptStreamAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(100)));
        }
예제 #4
0
        public async Task TestStreams()
        {
            using (QuicListener listener = new QuicListener(QuicImplementationProviders.Mock, new IPEndPoint(IPAddress.Loopback, 0), sslServerAuthenticationOptions: null))
            {
                listener.Start();

                IPEndPoint listenEndPoint = listener.ListenEndPoint;

                using (QuicConnection clientConnection = new QuicConnection(QuicImplementationProviders.Mock, listenEndPoint, sslClientAuthenticationOptions: null))
                {
                    Assert.False(clientConnection.Connected);
                    Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);

                    ValueTask      connectTask      = clientConnection.ConnectAsync();
                    QuicConnection serverConnection = await listener.AcceptConnectionAsync();

                    await connectTask;

                    Assert.True(clientConnection.Connected);
                    Assert.True(serverConnection.Connected);
                    Assert.Equal(listenEndPoint, serverConnection.LocalEndPoint);
                    Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);
                    Assert.Equal(clientConnection.LocalEndPoint, serverConnection.RemoteEndPoint);

                    await CreateAndTestBidirectionalStream(clientConnection, serverConnection);
                    await CreateAndTestBidirectionalStream(serverConnection, clientConnection);
                    await CreateAndTestUnidirectionalStream(serverConnection, clientConnection);
                    await CreateAndTestUnidirectionalStream(clientConnection, serverConnection);
                }
            }
        }
예제 #5
0
        public QuicConnectionListener(QuicTransportOptions options, IQuicTrace log, EndPoint endpoint, SslServerAuthenticationOptions sslServerAuthenticationOptions)
        {
            if (options.Alpn == null)
            {
                throw new InvalidOperationException("QuicTransportOptions.Alpn must be configured with a value.");
            }

            _log     = log;
            _context = new QuicTransportContext(_log, options);
            EndPoint = endpoint;
            var quicListenerOptions = new QuicListenerOptions();

            // TODO Should HTTP/3 specific ALPN still be global? Revisit whether it can be statically set once HTTP/3 is finalized.
            sslServerAuthenticationOptions.ApplicationProtocols = new List <SslApplicationProtocol>()
            {
                new SslApplicationProtocol(options.Alpn)
            };

            quicListenerOptions.ServerAuthenticationOptions = sslServerAuthenticationOptions;
            quicListenerOptions.ListenEndPoint = endpoint as IPEndPoint;
            quicListenerOptions.IdleTimeout    = options.IdleTimeout;

            _listener = new QuicListener(QuicImplementationProviders.MsQuic, quicListenerOptions);
            _listener.Start();
        }
예제 #6
0
        public async Task TestConnect()
        {
            SslServerAuthenticationOptions serverOpts = GetSslServerAuthenticationOptions();

            using QuicListener listener = new QuicListener(
                      QuicImplementationProviders.MsQuic,
                      new IPEndPoint(IPAddress.Loopback, 0),
                      serverOpts);

            listener.Start();
            IPEndPoint listenEndPoint = listener.ListenEndPoint;

            Assert.NotEqual(0, listenEndPoint.Port);

            using QuicConnection clientConnection = new QuicConnection(
                      QuicImplementationProviders.MsQuic,
                      listenEndPoint,
                      GetSslClientAuthenticationOptions());

            Assert.False(clientConnection.Connected);
            Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);

            ValueTask      connectTask      = clientConnection.ConnectAsync();
            QuicConnection serverConnection = await listener.AcceptConnectionAsync();

            await connectTask;

            Assert.True(clientConnection.Connected);
            Assert.True(serverConnection.Connected);
            Assert.Equal(listenEndPoint, serverConnection.LocalEndPoint);
            Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);
            Assert.Equal(clientConnection.LocalEndPoint, serverConnection.RemoteEndPoint);
            Assert.Equal(serverOpts.ApplicationProtocols[0].ToString(), clientConnection.NegotiatedApplicationProtocol.ToString());
            Assert.Equal(serverOpts.ApplicationProtocols[0].ToString(), serverConnection.NegotiatedApplicationProtocol.ToString());
        }
        public QuicConnectionListener(QuicTransportOptions options, IQuicTrace log, EndPoint endpoint)
        {
            if (options.Alpn == null)
            {
                throw new InvalidOperationException("QuicTransportOptions.Alpn must be configured with a value.");
            }

            _log     = log;
            _context = new QuicTransportContext(_log, options);
            EndPoint = endpoint;

            var quicListenerOptions = new QuicListenerOptions();
            var sslConfig           = new SslServerAuthenticationOptions();

            sslConfig.ServerCertificate    = options.Certificate;
            sslConfig.ApplicationProtocols = new List <SslApplicationProtocol>()
            {
                new SslApplicationProtocol(options.Alpn)
            };

            quicListenerOptions.ServerAuthenticationOptions = sslConfig;
            quicListenerOptions.CertificateFilePath         = options.CertificateFilePath;
            quicListenerOptions.PrivateKeyFilePath          = options.PrivateKeyFilePath;
            quicListenerOptions.ListenEndPoint = endpoint as IPEndPoint;
            quicListenerOptions.IdleTimeout    = TimeSpan.FromMinutes(2);

            _listener = new QuicListener(QuicImplementationProviders.MsQuic, quicListenerOptions);
            _listener.Start();
        }
예제 #8
0
        static void Main(string[] args)
        {
            DNSEncoder.Init();
            var listener = new QuicListener(11000);

            listener.Start();
            while (true)
            {
                var client = listener.AcceptQuicClient();

                client.OnDataReceived += c => {
                    var msg = c.Data;
                    using (var bgWorker = new BackgroundWorker())
                    {
                        bgWorker.DoWork += (sender, eventArgs) =>
                        {
                            var dnsQMsg = DnsMessage.Parse(msg);
                            var dnsRMsg =
                                new DnsClient(IPAddress.Parse("8.8.8.8"), 1000).SendMessage(dnsQMsg);
                            c.Send(DNSEncoder.Encode(dnsRMsg));

                            Console.ForegroundColor = ConsoleColor.Cyan;
                            dnsQMsg.Questions.ForEach(o => Console.WriteLine("Qu:" + o));
                            Console.ForegroundColor = ConsoleColor.Green;
                            dnsRMsg.AnswerRecords.ForEach(o => Console.WriteLine("An:" + o));
                            Console.ForegroundColor = ConsoleColor.DarkGreen;
                            dnsRMsg.AuthorityRecords.ForEach(o => Console.WriteLine("Au:" + o));
                            Console.ForegroundColor = ConsoleColor.Green;
                        };
                        bgWorker.RunWorkerAsync();
                    }
                };
            }
        }
예제 #9
0
        public QuicListener CreateQuicListener(IPEndPoint endpoint)
        {
            QuicListener listener = new QuicListener(QuicImplementationProviders.MsQuic, endpoint, GetSslServerAuthenticationOptions());

            listener.Start();
            return(listener);
        }
예제 #10
0
        public async Task TestConnect()
        {
            using QuicListener listener = CreateQuicListener();

            listener.Start();
            IPEndPoint listenEndPoint = listener.ListenEndPoint;

            using QuicConnection clientConnection = CreateQuicConnection(listenEndPoint);

            Assert.False(clientConnection.Connected);
            Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);

            ValueTask      connectTask      = clientConnection.ConnectAsync();
            QuicConnection serverConnection = await listener.AcceptConnectionAsync();

            await connectTask;

            Assert.True(clientConnection.Connected);
            Assert.True(serverConnection.Connected);
            Assert.Equal(listenEndPoint, serverConnection.LocalEndPoint);
            Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);
            Assert.Equal(clientConnection.LocalEndPoint, serverConnection.RemoteEndPoint);
            Assert.Equal(ApplicationProtocol.ToString(), clientConnection.NegotiatedApplicationProtocol.ToString());
            Assert.Equal(ApplicationProtocol.ToString(), serverConnection.NegotiatedApplicationProtocol.ToString());
        }
예제 #11
0
        static void Main(string[] args)
        {
            byte[]          bytes    = new VariableInteger(12345);
            VariableInteger integer  = bytes;
            UInt64          uinteger = integer;
            int             size     = VariableInteger.Size(bytes[0]);

            InitialPacket packet = new InitialPacket()
            {
                Version                 = 16,
                SourceConnectionId      = 124,
                DestinationConnectionId = 0,
                PacketNumber            = 777521,
                TokenLength             = 0
            };

            packet = new PacketCreator().CreateInitialPacket(124, 0);

            ConnectionCloseFrame frame     = new ConnectionCloseFrame(ErrorCode.SERVER_BUSY, "The server is too busy to process your request.");
            MaxStreamIdFrame     msidframe = new MaxStreamIdFrame(144123, StreamType.ClientUnidirectional);

            //packet.AttachFrame(frame);
            packet.AttachFrame(msidframe);

            byte[] data = packet.Encode();
            string b64  = ToBase64(data);

            byte[] shpdata1 = new byte[] { 1, 1, 2, 3, 5, 8 };
            byte[] shpdata2 = new byte[] { 13, 21, 34, 55, 89, 144 };

            ShortHeaderPacket shp = new ShortHeaderPacket();

            shp.DestinationConnectionId = 124;
            shp.PacketNumber            = 2;

            shp.AttachFrame(new StreamFrame()
            {
                StreamId = 1, Length = new VariableInteger((UInt64)shpdata2.Length), StreamData = shpdata2, Offset = 6, EndOfStream = true
            });
            shp.AttachFrame(new StreamFrame()
            {
                StreamId = 1, Length = new VariableInteger((UInt64)shpdata1.Length), StreamData = shpdata1, Offset = 0
            });

            string shpb64 = ToBase64(shp.Encode());

            packet.Decode(data);

            byte[] ccfData = frame.Encode();
            frame.Decode(new ByteArray(ccfData));

            byte[]   streamIdData = new StreamId(123, StreamType.ClientUnidirectional);
            StreamId streamId     = streamIdData;

            QuicListener listener = new QuicListener(11000);

            listener.OnClientConnected += Listener_OnClientConnected;
            listener.Start();
        }
예제 #12
0
 public void DoGlobalSetupQuicStream()
 {
     DoGlobalSetupShared();
     QuicListener = QuicFactory.CreateListener();
     QuicListener.Start();
     _serverTask = Task.Run(QuicStreamServer);
     GlobalSetupQuicStream();
 }
예제 #13
0
        static void Example()
        {
            QuicListener listener = new QuicListener(11000);

            listener.OnClientConnected += ClientConnected;

            listener.Start();

            Console.ReadKey();
        }
예제 #14
0
        internal static QuicListener CreateQuicListener(IPEndPoint endpoint)
        {
            QuicListener listener = new QuicListener(ImplementationProvider, new QuicListenerOptions()
            {
                ListenEndPoint = endpoint,
                ServerAuthenticationOptions = GetSslServerAuthenticationOptions(),
                CertificateFilePath         = "Certs/cert.crt",
                PrivateKeyFilePath          = "Certs/cert.key"
            });

            listener.Start();
            return(listener);
        }
예제 #15
0
        protected override async Task <StreamPair> CreateConnectedStreamsAsync()
        {
            QuicImplementationProvider provider = Provider;
            var protocol = new SslApplicationProtocol("quictest");

            var listener = new QuicListener(
                provider,
                new IPEndPoint(IPAddress.Loopback, 0),
                new SslServerAuthenticationOptions {
                ApplicationProtocols = new List <SslApplicationProtocol> {
                    protocol
                }
            });

            listener.Start();

            QuicConnection connection1 = null, connection2 = null;
            QuicStream     stream1 = null, stream2 = null;

            await WhenAllOrAnyFailed(
                Task.Run(async() =>
            {
                connection1 = await listener.AcceptConnectionAsync();
                stream1     = await connection1.AcceptStreamAsync();
            }),
                Task.Run(async() =>
            {
                connection2 = new QuicConnection(
                    provider,
                    listener.ListenEndPoint,
                    new SslClientAuthenticationOptions()
                {
                    ApplicationProtocols = new List <SslApplicationProtocol>()
                    {
                        protocol
                    }
                });
                await connection2.ConnectAsync();
                stream2 = connection2.OpenBidirectionalStream();
            }));

            var result = new StreamPairWithOtherDisposables(stream1, stream2);

            result.Disposables.Add(connection1);
            result.Disposables.Add(connection2);
            result.Disposables.Add(listener);

            return(result);
        }
        public QuicConnectionListener(QuicTransportOptions options, IQuicTrace log, EndPoint endpoint)
        {
            _log     = log;
            _context = new QuicTransportContext(_log, options);
            EndPoint = endpoint;
            var sslConfig = new SslServerAuthenticationOptions();

            sslConfig.ServerCertificate    = options.Certificate;
            sslConfig.ApplicationProtocols = new List <SslApplicationProtocol>()
            {
                new SslApplicationProtocol(options.Alpn)
            };
            _listener = new QuicListener(QuicImplementationProviders.MsQuic, endpoint as IPEndPoint, sslConfig);
            _listener.Start();
        }
예제 #17
0
        static void Main(string[] args)
        {
            QuicListener listener = new QuicListener(11000);

            listener.Start();
            while (true)
            {
                QuicConnection client = listener.AcceptQuicClient();

                client.OnDataReceived += (c) => {
                    byte[] data = c.Data;
                    Console.WriteLine("Data received: " + Encoding.UTF8.GetString(data));
                    c.Send(Encoding.UTF8.GetBytes("Echo!"));
                };
            }
        }
예제 #18
0
        static void Main()
        {
            int port = 8880;

            // Print the logs in the console
            Logger.StreamOutput           = new StreamWriter(Console.OpenStandardOutput());
            Logger.StreamOutput.AutoFlush = true;

            // Simulate 10% packet loss
            QuicConnection.PacketLossPercentage = 10;
            QuicListener server = new QuicListener(port);

            // We only use one chatroom in this sample, but multiple could be instantiated
            Chatroom chatroom = new Chatroom();

            Dictionary <QuicConnection, Thread> threads = new Dictionary <QuicConnection, Thread>();

            Console.WriteLine("Server listening on port : {0}", port);

            server.Start();

            while (true)
            {
                foreach (QuicConnection connection in server.getConnectionPool().GetPool())
                {
                    if (!chatroom.containsConnection(connection))
                    {
                        // Every new connection is added to the chatroom and a new listening thread is created
                        chatroom.addConnection(connection);
                        Thread t = new Thread(new ThreadStart(() => ProcessMessagesFromConnection(connection, chatroom)));
                        t.Start();
                        threads.Add(connection, t);
                    }
                }

                foreach (QuicConnection connection in chatroom.Connections)
                {
                    if (!server.getConnectionPool().GetPool().Contains(connection))
                    {
                        // Whenever a connection is closed by the client, we need to remove it from the chatroom and close the corresponding thread
                        chatroom.removeConnection(connection);
                        threads[connection].Abort();
                        threads.Remove(connection);
                    }
                }
            }
        }
예제 #19
0
        public async Task TestStreams()
        {
            using (QuicListener listener = new QuicListener(
                       QuicImplementationProviders.MsQuic,
                       new IPEndPoint(IPAddress.Loopback, 0),
                       GetSslServerAuthenticationOptions()))
            {
                listener.Start();
                IPEndPoint listenEndPoint = listener.ListenEndPoint;

                using (QuicConnection clientConnection = new QuicConnection(
                           QuicImplementationProviders.MsQuic,
                           listenEndPoint,
                           sslClientAuthenticationOptions: new SslClientAuthenticationOptions {
                    ApplicationProtocols = new List <SslApplicationProtocol>()
                    {
                        new SslApplicationProtocol("quictest")
                    }
                }))
                {
                    Assert.False(clientConnection.Connected);
                    Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);

                    ValueTask      connectTask      = clientConnection.ConnectAsync();
                    QuicConnection serverConnection = await listener.AcceptConnectionAsync();

                    await connectTask;

                    Assert.True(clientConnection.Connected);
                    Assert.True(serverConnection.Connected);
                    Assert.Equal(listenEndPoint, serverConnection.LocalEndPoint);
                    Assert.Equal(listenEndPoint, clientConnection.RemoteEndPoint);
                    Assert.Equal(clientConnection.LocalEndPoint, serverConnection.RemoteEndPoint);

                    await CreateAndTestBidirectionalStream(clientConnection, serverConnection);
                    await CreateAndTestBidirectionalStream(serverConnection, clientConnection);
                    await CreateAndTestUnidirectionalStream(serverConnection, clientConnection);
                    await CreateAndTestUnidirectionalStream(clientConnection, serverConnection);

                    await clientConnection.CloseAsync(errorCode : 0);
                }
            }
        }
예제 #20
0
        public Http3LoopbackServer(GenericLoopbackOptions options = null)
        {
            options ??= new GenericLoopbackOptions();

            _cert = Configuration.Certificates.GetSelfSigned13ServerCertificate();

            var sslOpts = new SslServerAuthenticationOptions
            {
                EnabledSslProtocols  = options.SslProtocols,
                ApplicationProtocols = new List <SslApplicationProtocol> {
                    new SslApplicationProtocol("h3-29")
                },
                //ServerCertificate = _cert,
                ClientCertificateRequired = false
            };

            _listener = new QuicListener(new IPEndPoint(options.Address, 0), sslOpts);
            _listener.Start();
        }
예제 #21
0
파일: Echo.cs 프로젝트: rzikm/master-thesis
        public static async Task <int> RunServer(IPEndPoint listenEp, string certificateFile, string privateKeyFile, CancellationToken token)
        {
            using QuicListener listener = new QuicListener(new QuicListenerOptions
            {
                ListenEndPoint              = listenEp,
                CertificateFilePath         = certificateFile,
                PrivateKeyFilePath          = privateKeyFile,
                ServerAuthenticationOptions = new SslServerAuthenticationOptions
                {
                    ApplicationProtocols = new List <SslApplicationProtocol>
                    {
                        new SslApplicationProtocol("echo")
                    }
                }
            });

            // QuicListener must be started before accepting connections.
            listener.Start();

            // tasks that need to be awaited when trying to exit gracefully
            List <Task> tasks = new List <Task>();

            try
            {
                QuicConnection conn;
                while ((conn = await listener.AcceptConnectionAsync(token)) != null)
                {
                    // copy the connection into a variable with narrower scope so
                    // that it is not shared among multiple lambdas
                    QuicConnection captured = conn;
                    var            task     = Task.Run(
                        () => HandleServerConnection(captured, token));
                    tasks.Add(task);
                }
            }
            finally
            {
                // wait until all connections are closed
                await Task.WhenAll(tasks);
            }

            return(0);
        }
예제 #22
0
        // RunAsync starts the QuicListener and continually waits for new clients
        public override async Task RunAsync(CancellationToken Token)
        {
            // Start the QuicListener
            QuicListener listener = new QuicListener(this.ExternalPort);

            //QuicListener Listener = new QuicListener(IPAddress.Any, this.ExternalPort);;
            listener.Start();

            // Continually wait for new client
            while (!Token.IsCancellationRequested)
            {
                // Handle the client asynchronously in a new thread
                QuicConnection client = listener.AcceptQuicClient();
                _ = Task.Run(() =>
                {
                    //client.ReceiveTimeout = client.SendTimeout = 0;
                    QuicStream stream = client.CreateStream(QuickNet.Utilities.StreamType.ClientBidirectional);
                    //stream.
                    //stream.ReadTimeout = stream.WriteTimeout = Timeout.Infinite;
                    while (!Token.IsCancellationRequested)
                    {
                        // byte[] data;
                        // Read from the implant
                        string read            = "";
                        client.OnDataReceived += (c) =>
                        {
                            read += Encoding.UTF8.GetString(c.Data);
                        };
                        //string read = Encoding.UTF8.GetString(data);
                        //string read = await Utilities.ReadStreamAsync(stream);
                        // Write to the Covenant server
                        string guid = this.WriteToConnector(read);
                        if (guid != null)
                        {
                            // Track this GUID -> client mapping, for use within the OnReadBridge function

                            Clients.TryAdd(guid, stream);
                        }
                    }
                });
            }
        }
예제 #23
0
        public static (IPEndPoint listenEp, Task finished) StartQuic(IPEndPoint endpoint, string certPath, string keyPath,
                                                                     CancellationToken cancellationToken)
        {
            TaskCompletionSource completionSource = new TaskCompletionSource();

            var options = new QuicListenerOptions
            {
                CertificateFilePath         = certPath,
                PrivateKeyFilePath          = keyPath,
                ListenEndPoint              = endpoint,
                ServerAuthenticationOptions = new SslServerAuthenticationOptions
                {
                    ApplicationProtocols = new List <SslApplicationProtocol>
                    {
                        Helpers.AlpnProtocol
                    }
                },
                MaxBidirectionalStreams = 1024
            };

            var listener = new QuicListener(options);

            listener.Start();

            List <Task> currentConnectionTasks = new List <Task>();

            Helpers.Dispatch(async() =>
            {
                while (true)
                {
                    var connection = await listener.AcceptConnectionAsync().ConfigureAwait(false);
                    Helpers.Trace("New connection");
                    var task = Helpers.Dispatch(() => ServerConnectionTask(connection, cancellationToken));
                    currentConnectionTasks.Add(task);
                }
            });

            cancellationToken.Register(() =>
                                       Task.WhenAll(currentConnectionTasks).ContinueWith(_ => completionSource.SetResult()));

            return(listener.ListenEndPoint, completionSource.Task);
        }
예제 #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Server");
            QuicListener listener = new QuicListener(18000);

            listener.Start();
            while (true)
            {
                // Blocks while waiting for a connection
                QuicConnection client = listener.AcceptQuicClient();

                // Assign an action when a data is received from that client.
                client.OnDataReceived += (c) => {
                    byte[] data = c.Data;
                    Console.WriteLine("Data received: " + Encoding.UTF8.GetString(data));
                    // Echo back data to the client
                    c.Send(Encoding.UTF8.GetBytes("Echo!"));
                };
            }
        }
예제 #25
0
        static void Example()
        {
            QuicListener listener = new QuicListener(11000);

            listener.Start();

            while (true)
            {
                // Blocks while waiting for a connection
                QuicConnection client = listener.AcceptQuicClient();

                // Assign an action when a data is received from that client.
                client.OnDataReceived += (c) => {
                    byte[] data = c.Data;

                    Console.WriteLine("Data received: " + Encoding.UTF8.GetString(data));

                    c.Send(Encoding.UTF8.GetBytes("Echo!"));
                    c.Send(Encoding.UTF8.GetBytes("Echo2!"));
                };
            }
        }
예제 #26
0
        public async Task BasicTest()
        {
            using (QuicListener listener = new QuicListener(QuicImplementationProviders.Mock, new IPEndPoint(IPAddress.Loopback, 0), sslServerAuthenticationOptions: null))
            {
                listener.Start();
                IPEndPoint listenEndPoint = listener.ListenEndPoint;

                await Task.WhenAll(
                    Task.Run(async() =>
                {
                    // Client code
                    using (QuicConnection connection = new QuicConnection(QuicImplementationProviders.Mock, listenEndPoint, sslClientAuthenticationOptions: null))
                    {
                        await connection.ConnectAsync();
                        using (QuicStream stream = connection.OpenBidirectionalStream())
                        {
                            await stream.WriteAsync(s_data);
                        }
                    }
                }),
                    Task.Run(async() =>
                {
                    // Server code
                    using (QuicConnection connection = await listener.AcceptConnectionAsync())
                    {
                        using (QuicStream stream = await connection.AcceptStreamAsync())
                        {
                            byte[] buffer = new byte[s_data.Length];
                            int bytesRead = await stream.ReadAsync(buffer);
                            Assert.Equal(s_data.Length, bytesRead);
                            Assert.True(s_data.Span.SequenceEqual(buffer));
                        }
                    }
                }));
            }
        }
예제 #27
0
        private static async Task Server(CancellationToken cancellationToken)
        {
            try
            {
                Console.WriteLine(@"Starting listener");
                using var listener = new QuicListener(QuicImplementationProviders.Managed, new QuicListenerOptions
                {
                    ListenEndPoint = serverEndpoint,
                    ServerAuthenticationOptions = new SslServerAuthenticationOptions
                    {
                        ApplicationProtocols = new List <SslApplicationProtocol>
                        {
                            new SslApplicationProtocol("sample")
                        }
                    },
                    CertificateFilePath = "Certs/cert.crt",
                    PrivateKeyFilePath  = "Certs/cert.key"
                });

                listener.Start();

                Console.WriteLine($@"listening on {listener.ListenEndPoint}");

                Console.WriteLine("Waiting for incoming connection...");
                using var connection = await listener.AcceptConnectionAsync(cancellationToken).ConfigureAwait(false);

                Console.WriteLine("Connection accepted, opening stream");
                var stream = connection.OpenUnidirectionalStream();

                Console.WriteLine($"Writing {DataSizeBytes} bytes of data");
                var buffer = new byte[1024 * 16];

                // write known data so that we can assert it on the other size
                for (var i = 0; i < buffer.Length; i++)
                {
                    buffer[i] = (byte)i;
                }

                var written = 0;

                while (written < DataSizeBytes)
                {
                    await stream.WriteAsync(buffer, cancellationToken).ConfigureAwait(false);

                    written += buffer.Length;
                }

                stream.Shutdown();
                await stream.FlushAsync(cancellationToken).ConfigureAwait(false);

                Console.WriteLine("Data written, closing.");

                await stream.ShutdownWriteCompleted(cancellationToken).ConfigureAwait(false);

                Console.WriteLine("Server shutdown complete");

                await stream.DisposeAsync();

                Console.WriteLine("Server stream dispose");

                connection.Dispose();
                Console.WriteLine("Server connection disposed");
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception at server:");
                Console.WriteLine(e);
                throw;
            }
        }
예제 #28
0
        protected static async Task <StreamPair> CreateConnectedStreamsAsync()
        {
            QuicImplementationProvider provider = ImplementationProvider;
            var protocol = new SslApplicationProtocol("quictest");

            QuicListener listener = new QuicListener(provider, new QuicListenerOptions()
            {
                ListenEndPoint = new IPEndPoint(IPAddress.Loopback, 0),
                ServerAuthenticationOptions = new SslServerAuthenticationOptions {
                    ApplicationProtocols = new List <SslApplicationProtocol> {
                        protocol
                    }
                },
                CertificateFilePath = "Certs/cert.crt",
                PrivateKeyFilePath  = "Certs/cert.key"
            });

            listener.Start();

            QuicConnection connection1 = null, connection2 = null;
            QuicStream     stream1 = null, stream2 = null;

            await Task.WhenAll(
                Task.Run(async() =>
            {
                connection1 = await listener.AcceptConnectionAsync();
                stream1     = await connection1.AcceptStreamAsync();

                // Hack to force stream creation
                byte[] buffer = new byte[1];
                await stream1.ReadAsync(buffer);
            }),
                Task.Run(async() =>
            {
                connection2 = new QuicConnection(
                    provider,
                    listener.ListenEndPoint,
                    new SslClientAuthenticationOptions()
                {
                    ApplicationProtocols = new List <SslApplicationProtocol>()
                    {
                        protocol
                    }
                });
                await connection2.ConnectAsync();
                stream2 = connection2.OpenBidirectionalStream();

                // Hack to force stream creation
                byte[] buffer = new byte[1];
                await stream2.WriteAsync(buffer);
                await stream2.FlushAsync();
            }));

            var result = new StreamPair(stream1, stream2);

            result.Disposables.Add(connection1);
            result.Disposables.Add(connection2);
            result.Disposables.Add(listener);

            return(result);
        }