Пример #1
0
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

#pragma warning disable 4014
            ProducerConsumer.CreateAsync(

                c => _transportListener.AcceptTransportAsync(c),
                async t =>
            {
                await t.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    t,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                var clientNode = new Node("client", "msging.net", "instance");

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                },
                    (n, a) => new AuthenticationResult(null, clientNode).AsCompletedTask(), _cts.Token);

                var channelListener = new ChannelListener(
                    m => TaskUtil.TrueCompletedTask,
                    n => TaskUtil.TrueCompletedTask,
                    async c =>
                {
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);

                return(true);
            },
                _cts.Token);
        }
Пример #2
0
        protected ChannelListener GetAndStartTarget()
        {
            if (_createdTargets == null)
            {
                _createdTargets = new List <ChannelListener>();
            }

            var target = new ChannelListener(_messageConsumer, _notificationConsumer, _commandConsumer);

            target.Start(_channel.Object);
            _createdTargets.Add(target);
            return(target);
        }
Пример #3
0
        private void StartEnvelopeListeners()
        {
            _cts = new CancellationTokenSource();
            var messageHandler      = new MessageReceivedHandler(_sender, _autoNotify, EnvelopeManager, _cts);
            var notificationHandler = new NotificationReceivedHandler(_sender, EnvelopeManager, _cts);
            var commandHandler      = new CommandReceivedHandler(_sender, EnvelopeManager, _cts);

            _channelListener = new ChannelListener(
                m => messageHandler.HandleAsync(m, _cts.Token),
                n => notificationHandler.HandleAsync(n, _cts.Token),
                c => commandHandler.HandleAsync(c, _cts.Token));
            _channelListener.Start(_connection.OnDemandClientChannel);
        }
Пример #4
0
        static async Task MainAsync(string[] args)
        {
            Console.Write("Host name (ENTER for default): ");

            var hostName = Console.ReadLine();

            if (string.IsNullOrWhiteSpace(hostName))
            {
                hostName = Dns.GetHostName();
            }

            Console.Write("Port number (ENTER for default): ");

            int portNumber;

            if (!int.TryParse(Console.ReadLine(), out portNumber))
            {
                portNumber = 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: "******"net.tcp://{hostName}:{portNumber}");
            var transport = new TcpTransport(traceWriter: new DebugTraceWriter());

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transport, serverUri)
                          .AddBuiltHandler((channel, token) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(TaskUtil.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .AddEstablishedHandler(async(c, t) =>
                                                 await c.SetResourceAsync(
                                                     new LimeUri(UriTemplates.PRESENCE),
                                                     new Presence()
            {
                Status = PresenceStatus.Available
            },
                                                     t))
                          .AddEstablishedHandler(async(c, t) =>
                                                 await c.SetResourceAsync(
                                                     new LimeUri(UriTemplates.RECEIPT),
                                                     new Receipt()
            {
                Events = new[] { Event.Received, Event.Dispatched }
            },
                                                     t));

            if (identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(identity)
                          .WithPlainAuthentication(password);
            }

            var onDemandChannel = new OnDemandClientChannel(builder);
            var running         = true;

            onDemandChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                Console.Write("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);
            });

            channelListener.Start(onDemandChannel);

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

                Node to = null;
                if (string.IsNullOrEmpty(toInput) || Node.TryParse(toInput, out to))
                {
                    Console.Write("Message text: ");
                    var message = new Message
                    {
                        To      = to,
                        Content = new PlainText
                        {
                            Text = Console.ReadLine()
                        }
                    };

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

            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();
        }
Пример #5
0
        static async Task Main(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): ");
            if (!Identity.TryParse(Console.ReadLine(), out var identity))
            {
                identity = null;
            }

            string password = null;

            if (identity != null)
            {
                Console.Write("Password: "******"Number of channels (ENTER for 1): ");
            if (!int.TryParse(Console.ReadLine(), out var channelCount))
            {
                channelCount = 1;
            }

            var setPresence = false;
            var setReceipts = false;

            // Creates a new transport and connect to the server
            var serverUri = new Uri(serverUriValue);
            Func <ITransport> transportFactory = () => CreateTransportForUri(serverUri);

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transportFactory, serverUri)
                          .AddBuiltHandler((channel, token) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(TaskUtil.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .WithEncryption(SessionEncryption.None)
                          .AddEstablishedHandler(async(c, t) =>
            {
                if (setPresence)
                {
                    await c.SetResourceAsync(
                        new LimeUri(UriTemplates.PRESENCE),
                        new Presence()
                    {
                        Status      = PresenceStatus.Available,
                        RoutingRule = RoutingRule.Identity,
                        RoundRobin  = true
                    },
                        t);
                }
            })
                          .AddEstablishedHandler(async(c, t) =>
            {
                if (setReceipts)
                {
                    await c.SetResourceAsync(
                        new LimeUri(UriTemplates.RECEIPT),
                        new Receipt()
                    {
                        Events = new[] { Event.Received, Event.Consumed }
                    },
                        t);
                }
            });

            if (identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(identity)
                          .WithPlainAuthentication(password);
            }

            IOnDemandClientChannel onDemandClientChannel;

            if (channelCount == 1)
            {
                onDemandClientChannel = new OnDemandClientChannel(builder);
            }
            else
            {
                onDemandClientChannel = new MultiplexerClientChannel(builder);
            }

            var running = true;

            onDemandClientChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                Console.Write("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 onDemandClientChannel.EstablishAsync(CancellationToken.None);

            channelListener.Start(onDemandClientChannel);

            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 onDemandClientChannel.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 onDemandClientChannel.FinishAsync(CancellationToken.None);

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Пример #6
0
        private static async Task <IOnDemandClientChannel> EstablishChannelAsync(ConnectionInformation connectionInformation, CancellationToken cancellationToken)
        {
            ITransport transportFactory() => CreateTransportForUri(connectionInformation.ServerUri);

            // Creates a new client channel
            var builder = ClientChannelBuilder
                          .Create(transportFactory, connectionInformation.ServerUri)
                          .AddBuiltHandler((channel, handlerCancellationToken) =>
            {
                channel.CommandModules.Add(new ReplyPingChannelModule(channel));
                return(Task.CompletedTask);
            })
                          .CreateEstablishedClientChannelBuilder()
                          .WithEncryption(SessionEncryption.None)
                          .WithInstance(connectionInformation.Instance)
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                await channel.SetResourceAsync(
                    new LimeUri(UriTemplates.PRESENCE),
                    connectionInformation.Presence,
                    handlerCancellationToken);
            })
                          .AddEstablishedHandler(async(channel, handlerCancellationToken) =>
            {
                await channel.SetResourceAsync(
                    new LimeUri(UriTemplates.RECEIPT),
                    connectionInformation.Receipt,
                    handlerCancellationToken);
            });

            if (connectionInformation.Identity == null)
            {
                builder = builder.WithAuthentication <GuestAuthentication>();
            }
            else
            {
                builder = builder
                          .WithIdentity(connectionInformation.Identity)
                          .WithPlainAuthentication(connectionInformation.Password);
            }

            var clientChannel = new OnDemandClientChannel(builder);

            clientChannel.ChannelCreationFailedHandlers.Add(information =>
            {
                WriteError("Could not establish the session: {0}", information.Exception.Message);
                return(TaskUtil.FalseCompletedTask);
            });

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


            await clientChannel.EstablishAsync(cancellationToken);

            channelListener.Start(clientChannel);

            return(clientChannel);
        }
Пример #7
0
 public void Start(IEstablishedReceiverChannel channel)
 {
     _channelListener.Start(channel);
     ReceiverChannel = channel;
     Started         = true;
 }
        public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await ListenerSemaphore.WaitAsync(cancellationToken);

            await _transportListener.StartAsync();

            ProducerConsumer.CreateAsync(
                c => _transportListener.AcceptTransportAsync(c),
                async(transport, _) =>
            {
                await transport.OpenAsync(null, _cts.Token);

                var serverChannel = new ServerChannel(
                    Guid.NewGuid().ToString(),
                    new Node("postmaster", "msging.net", "instance"),
                    transport,
                    TimeSpan.FromSeconds(60),
                    autoReplyPings: true);

                await serverChannel.EstablishSessionAsync(
                    new[] { SessionCompression.None },
                    new[] { SessionEncryption.None },
                    new[]
                {
                    AuthenticationScheme.Guest,
                    AuthenticationScheme.Key,
                    AuthenticationScheme.Plain,
                    AuthenticationScheme.Transport,
                    AuthenticationScheme.External
                },
                    (n, a, _) =>
                {
                    Authentications.Enqueue(a);
                    return(new AuthenticationResult(DomainRole.RootAuthority, a).AsCompletedTask());
                },
                    (n, s, c) =>
                {
                    return(n.AsCompletedTask());
                }, _cts.Token);

                var channelListener = new ChannelListener(
                    m =>
                {
                    Messages.Enqueue(m);
                    return(TaskUtil.TrueCompletedTask);
                },
                    n =>
                {
                    Notifications.Enqueue(n);
                    return(TaskUtil.TrueCompletedTask);
                },
                    async c =>
                {
                    Commands.Enqueue(c);
                    if (c.Status == CommandStatus.Pending)
                    {
                        await serverChannel.SendCommandAsync(
                            new Command(c.Id)
                        {
                            Status = CommandStatus.Success,
                            Method = c.Method
                        },
                            _cts.Token);
                    }
                    return(true);
                });

                channelListener.Start(serverChannel);
                Channels.Enqueue(serverChannel);

                return(true);
            },
                _cts.Token);
        }