コード例 #1
0
 private void StopEnvelopeListeners()
 {
     try
     {
         _channelListener?.Stop();
         _cts?.Cancel();
         _channelListener?.Dispose();
         _cts?.Dispose();
     }
     catch (ObjectDisposedException) { }
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: gecambridge/lime-csharp
        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();
        }
コード例 #3
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();
        }
コード例 #4
0
 public void Stop()
 {
     _channelListener.Stop();
     Started = false;
 }