Пример #1
0
        static async Task Main(string[] args)
        {
            var mailboxName = GetMailboxName(args);

            // Server will only support Https on Windows and Linux
            var credentials = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ChannelCredentials.Insecure : ClientResources.SslCredentials;

            var channel = new Channel("localhost:50051", credentials);

            Console.WriteLine($"Connecting to mailbox '{mailboxName}'");
            Console.WriteLine();

            await channel.ConnectAsync();

            Console.WriteLine("Connected");
            Console.WriteLine("Press escape to disconnect. Press any other key to forward mail.");

            var client = new Mailer.MailerClient(channel);

            using (var mailbox = client.Mailbox(headers: new Metadata {
                new Metadata.Entry("mailbox-name", mailboxName)
            }))
            {
                _ = Task.Run(async() =>
                {
                    while (await mailbox.ResponseStream.MoveNext(CancellationToken.None))
                    {
                        var response = mailbox.ResponseStream.Current;

                        Console.ForegroundColor = response.Reason == MailboxMessage.Types.Reason.Received ? ConsoleColor.White : ConsoleColor.Green;
                        Console.WriteLine();
                        Console.WriteLine(response.Reason == MailboxMessage.Types.Reason.Received ? "Mail received" : "Mail forwarded");
                        Console.WriteLine($"New mail: {response.New}, Forwarded mail: {response.Forwarded}");
                        Console.ResetColor();
                    }
                });

                while (true)
                {
                    var result = Console.ReadKey(intercept: true);
                    if (result.Key == ConsoleKey.Escape)
                    {
                        break;
                    }

                    await mailbox.RequestStream.WriteAsync(new ForwardMailMessage());
                }

                await mailbox.RequestStream.CompleteAsync();
            }

            Console.WriteLine("Disconnecting");
            await channel.ShutdownAsync();

            Console.WriteLine("Disconnected. Press any key to exit.");
            Console.ReadKey();
        }
Пример #2
0
        static async Task Main(string[] args)
        {
            var mailboxName = GetMailboxName(args);

            Console.WriteLine($"Creating client to mailbox '{mailboxName}'");
            Console.WriteLine();

            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var invoker = channel.Intercept(new ClientLoggerInterceptor());
            var client  = new Mailer.MailerClient(invoker);

            Console.WriteLine("Client created.");
            Console.WriteLine("Press escape to disconnect. Press any other key to forward mail.");

            using (var call = client.Mailbox(headers: new Grpc.Core.Metadata {
                new Metadata.Entry("mailbox-name", mailboxName)
            }))
            {
                var responseTask = Task.Run(async() =>
                {
                    await foreach (var message in call.ResponseStream.ReadAllAsync())
                    {
                        Console.ForegroundColor = message.Reason == MailboxMessage.Types.Reason.Received ? ConsoleColor.White : ConsoleColor.Green;
                        Console.WriteLine();
                        Console.WriteLine(message.Reason == MailboxMessage.Types.Reason.Received ? "Mail received" : "Mail forwarded");
                        Console.WriteLine($"New mail:{message.New},Forwarded mail:{message.Forwarded}");
                        Console.ResetColor();
                    }
                });

                while (true)
                {
                    var result = Console.ReadKey(intercept: true);
                    if (result.Key == ConsoleKey.Escape)
                    {
                        break;
                    }

                    await call.RequestStream.WriteAsync(new ForwardMailMessage());
                }

                Console.WriteLine("Disconnecting");
                await call.RequestStream.CompleteAsync();

                await responseTask;
            }



            Console.WriteLine("Disconnected. Press any key to exit...");
            Console.ReadKey();
        }
Пример #3
0
        public override async Task OnConnectedAsync()
        {
            var userId       = long.Parse(Context.UserIdentifier);
            var nickname     = Context.User.FindFirst("nickname").Value;
            var headicon     = Context.User.FindFirst("headicon").Value;
            var mailMetadata = new Mail.MailMetadata {
                UserId = userId, NickName = nickname, HeadIcon = headicon
            };

            var _client = new Mailer.MailerClient(ChannelService.Channel);
            var _call   = _client.Mailbox(headers: new Metadata {
                new Metadata.Entry("mailbox-name", "agent"),
                new Metadata.Entry("metadata" + Metadata.BinaryHeaderSuffix, mailMetadata.ToByteArray())
            });

            Context.Items.Add("_client", _client);
            Context.Items.Add("_call", _call);

            var CancellationToken = Context.ConnectionAborted;
            var ConnectionId      = Context.ConnectionId;
            var HttpContext       = Context.GetHttpContext();

            _ = Task.Run(async() =>
            {
                await foreach (var message in _call.ResponseStream.ReadAllAsync())
                {
                    var packet = new NetPacket {
                        Id = message.Id, Content = message.Content.ToBase64(), Reserve = message.Reserve
                    };
                    await _hubContext.Clients.Client(ConnectionId).SendAsync("StoCMessage", packet);
                    if (message.Id == 999999)
                    {
                        break;
                    }
                }

                if (!CancellationToken.IsCancellationRequested)
                {
                    HttpContext.Abort();
                }
                //Console.ForegroundColor = ConsoleColor.Green;
                //Console.WriteLine("!!!end");
                //Console.ResetColor();
            });

            await base.OnConnectedAsync();
        }
Пример #4
0
        public void Start()
        {
            if (Sourse != null && !Sourse.IsCancellationRequested)
            {
                return;
            }

            Sourse = new CancellationTokenSource();

            var callOptions = new CallOptions(new Metadata {
                new Metadata.Entry("mailbox-name", "game")
            }, cancellationToken: Sourse.Token);
            var _call = _client.Mailbox(callOptions.WithWaitForReady());

            _ = Task.Run(async() =>
            {
                var incomeMailQueue = _dbMailQueueRepository.GetIncomeMailQueue();
                await foreach (var message in _call.ResponseStream.ReadAllAsync(Sourse.Token))
                {
                    await incomeMailQueue.WriteAsync(new MailPacket {
                        Id      = message.Id, Content = message.Content.ToByteArray(),
                        Reserve = message.Reserve, UserId = message.UserId, ClientId = message.ClientId
                    });
                }
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("!!!end");
                Console.ResetColor();
            }, Sourse.Token);


            _ = Task.Run(async() =>
            {
                while (!Sourse.Token.IsCancellationRequested)
                {
                    try
                    {
                        if (CurrentMail == null)
                        {
                            if (await _mailChannel.Reader.WaitToReadAsync(Sourse.Token))
                            {
                                if (_mailChannel.Reader.TryRead(out var mail))
                                {
                                    CurrentMail = mail;
                                    await WriteDBMail(CurrentMail);
                                    CurrentMail = null;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            await WriteDBMail(CurrentMail);
                            CurrentMail = null;
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogWarning(e.Message);
                        Sourse.Cancel();
                    }
                }
            }, Sourse.Token);

            async Task WriteDBMail(MailPacket mail)
            {
                var forward = new ForwardMailMessage
                {
                    Id      = mail.Id,
                    Content = mail.Content != null?Google.Protobuf.ByteString.CopyFrom(mail.Content) : Google.Protobuf.ByteString.Empty,
                                  Reserve = mail.ClientId, UserId = mail.UserId, ClientId = mail.ClientId
                };

                try
                {
                    await _call.RequestStream.WriteAsync(forward);
                }
                catch (Exception e)
                {
                    _logger.LogWarning(e.Message);
                    Sourse.Cancel();
                    EventCancelled?.Invoke(_type);
                }
            }
        }