Пример #1
0
        static async Task MainAsync(string[] args)
        {
            Console.Write("Server URI (ENTER for default): ");

            var serverUriValue = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(serverUriValue))
            {
                serverUriValue = $"net.tcp://{Dns.GetHostName()}:{55321}";
            }

            Console.Write("Identity (name@domain - ENTER for none): ");

            Identity identity;

            if (!Identity.TryParse(Console.ReadLine(), out identity))
            {
                identity = null;
            }

            string password = null;

            if (identity != null)
            {
                Console.Write("Password: "******"Could not establish the session: {0}", information.Exception.Message);
                Console.WriteLine();
                running = false;
                return(TaskUtil.FalseCompletedTask);
            });


            var channelListener = new ChannelListener(message =>
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("Message with id '{0}' received from '{1}': {2}", message.Id, message.GetSender(),
                                  message.Content);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      notification =>
            {
                Console.ForegroundColor = ConsoleColor.DarkBlue;
                Console.WriteLine("Notification with id {0} received from '{1}' - Event: {2}",
                                  notification.Id, notification.GetSender(), notification.Event);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            },
                                                      command =>
            {
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("Command with id '{0}' received from '{1}' - Method: {2} - URI: {3}", command.Id,
                                  command.GetSender(), command.Method, command.Uri);
                Console.ResetColor();
                return(TaskUtil.TrueCompletedTask);
            });


            await onDemandChannel.EstablishAsync(CancellationToken.None);

            channelListener.Start(onDemandChannel);

            while (running)
            {
                Console.Write("Destination node (Type EXIT to quit): ");
                var toInput = Console.ReadLine();
                if (toInput != null &&
                    toInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }

                Node to = null;
                if (string.IsNullOrEmpty(toInput) || Node.TryParse(toInput, out to))
                {
                    Console.Write("Message text: ");
                    var text = Console.ReadLine();

                    var stopwatch = Stopwatch.StartNew();

                    Console.Write("Number of times to send (ENTER to 1): ");
                    int count;
                    if (!int.TryParse(Console.ReadLine(), out count))
                    {
                        count = 1;
                    }

                    await Task.WhenAll(
                        Enumerable
                        .Range(0, count)
                        .Select(async i =>
                    {
                        var message = new Message
                        {
                            Id      = i.ToString(),
                            To      = to,
                            Content = new PlainText
                            {
                                Text = text
                            }
                        };

                        await onDemandChannel.SendMessageAsync(message, CancellationToken.None);
                    }));

                    stopwatch.Stop();
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
                    Console.ResetColor();
                }
            }

            channelListener.Stop();
            await Task.WhenAll(
                channelListener.MessageListenerTask,
                channelListener.NotificationListenerTask,
                channelListener.CommandListenerTask);

            await onDemandChannel.FinishAsync(CancellationToken.None);

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Пример #2
0
        static async Task MainAsync(string[] args)
        {
            WriteLine("Starting the server...");

            var messageBufferBlock = new BufferBlock <Message>(
                new DataflowBlockOptions
            {
                BoundedCapacity = DataflowBlockOptions.Unbounded
            }
                );
            var messageActionBlock = new ActionBlock <Message>(
                ReceiveMessageAsync,
                new ExecutionDataflowBlockOptions
            {
                MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
                EnsureOrdered          = false
            });

            messageBufferBlock.LinkTo(messageActionBlock);

            var uri = new Uri("net.tcp://*****:*****@msging.net/default",
                new TcpTransportListener(uri, null, new EnvelopeSerializer(new DocumentTypeResolver())))
                         .WithChannelConsumers(m => messageBufferBlock.SendAsync(m), n => TaskUtil.TrueCompletedTask, c => TaskUtil.TrueCompletedTask)
                         .WithEnabledEncryptionOptions(new SessionEncryption[] { SessionEncryption.TLS })
                         .WithExceptionHandler(e =>
            {
                ForegroundColor = ConsoleColor.Red;
                WriteLine(e.ToString());
                ResetColor();
                return(Task.CompletedTask);
            })
                         .Build();


            await server.StartAsync(CancellationToken.None);

            using (var cts = new CancellationTokenSource())
            {
                WriteLine("Server started.");
                WriteLine("Starting the client...");

                var channelBuilder = ClientChannelBuilder
                                     .Create(() => new TcpTransport(new EnvelopeSerializer(new DocumentTypeResolver())), uri)
                                     .CreateEstablishedClientChannelBuilder()
                                     .WithEncryption(SessionEncryption.TLS);


                var client = new MultiplexerClientChannel(channelBuilder);
                await client.EstablishAsync(CancellationToken.None);

                //var client = await channelBuilder.BuildAndEstablishAsync(CancellationToken.None);

                WriteLine("Client started.");

                var reportTask = Task.Run(() => DoReport(cts.Token), cts.Token);

                while (true)
                {
                    SetCursorPosition(0, 5);
                    Write("                                                 ");
                    Write("                                                 ");
                    Write("                                                 ");
                    Write("                                                 ");
                    Write("                                                 ");
                    SetCursorPosition(0, 5);


                    Write("Number of tasks (ENTER for default): ");
                    if (!int.TryParse(Console.ReadLine(), out var taskCount))
                    {
                        taskCount = 10;
                    }

                    Write("Number of messages (ENTER for default): ");
                    if (!int.TryParse(Console.ReadLine(), out var messagesCount))
                    {
                        messagesCount = 1000;
                    }

                    Reset();

                    var stopwatch = Stopwatch.StartNew();

                    await Task.WhenAll(
                        Enumerable
                        .Range(0, taskCount)
                        .Select(i => Task.Run(async() =>
                    {
                        for (int j = 0; j < messagesCount; j++)
                        {
                            await client.SendMessageAsync(new Message()
                            {
                                Id      = $"{i}_{j}",
                                Content = "Testing a message"
                            },
                                                          CancellationToken.None);
                        }
                    })));

                    stopwatch.Stop();

                    WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms             ");
                }

                cts.Cancel();
                await reportTask;
            }

            await server.StopAsync(CancellationToken.None);

            WriteLine("Server stopped. Press ENTER to exit.");
            ReadLine();
        }