Esempio n. 1
0
        private async void btn_send_Click(object sender, RoutedEventArgs e)
        {
            if (isConnected == false)
            {
                MessageBox.Show("Ups! You forgot to connect!", "Error!");
            }
            else
            {
                if (txt_message.Text.ToString() == "")
                {
                    MessageBox.Show("Ups! You forgot to enter your message!", "Error!");
                }
                else
                {
                    clientMessage.Name        = client.Name;
                    clientMessage.Textmessage = txt_message.Text.ToString();

                    var chat = new ChatService.ChatServiceClient(channel);
                    chat.sendMessage(clientMessage);

                    UpdateChat();

                    if (stream != null)
                    {
                        await stream.RequestStream.WriteAsync(clientMessage);
                    }
                }
            }
        }
Esempio n. 2
0
        public static ChatService.ChatServiceClient CreateClient()
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new ChatService.ChatServiceClient(channel);

            return(client);
        }
Esempio n. 3
0
        public IChatServiceClientWrapper GetChatSercviceClient()
        {
            var channel           = GetChannel("Chat");
            var chatServiceClient = new ChatService.ChatServiceClient(channel);

            return(new ChatServiceClientWrapper(chatServiceClient, _logServiceFactory));
        }
Esempio n. 4
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     chatServer       = new ChatService.ChatServiceClient();
     tmrSync          = new Timer();
     tmrSync.Interval = 1000;
     tmrSync.Tick    += TmrSync_Tick;
 }
Esempio n. 5
0
        private async void UpdateChat()
        {
            var chat = new ChatService.ChatServiceClient(channel);

            try
            {
                using (stream = chat.chatStream())
                {
                    while (await stream.ResponseStream.MoveNext(CancellationToken.None))
                    {
                        //var serverMessage = stream.ResponseStream.Current;

                        //var displayMessage = string.Format("{0}:{1}{2}", serverMessage.Name, serverMessage.Textmessage, Environment.NewLine);
                        //chatbox.Text += displayMessage;

                        var serverMessage      = stream.ResponseStream.Current;
                        var otherClientMessage = serverMessage.Textmessage;
                        var displayMessage     = string.Format("{0}:{1}{2}", otherClientMessage.From, otherClientMessage.Message, Environment.NewLine);
                        chatbox.Text += displayMessage;
                    }
                }
            }
            catch (RpcException)
            {
                stream = null;
                throw;
            }
        }
        static void Main(string[] args)
        {
            ChatService.IChatService service = new ChatService.ChatServiceClient();

            Console.WriteLine("What is you're name?");
            String name = Console.ReadLine();


            Console.WriteLine("Loading messages...");

            ChatService.Message[] messages = service.GetMessages();
            PrintMessages(messages);

            String line = Console.ReadLine();
            while (!line.Equals("exit"))
            {
                ChatService.Message message = new ChatService.Message()
                {
                    Content = line,
                    User = name,
                };
                messages = service.SendMessage(message);
                PrintMessages(messages);
                line = Console.ReadLine();


            }
        }
        private static async Task SendMessageAsync(ChannelBase channel)
        {
            var chatService = new ChatService.ChatServiceClient(channel);

            try
            {
                var messageContent = string.Empty;
                while (messageContent != "exit")
                {
                    Console.WriteLine("Enter message: ");
                    messageContent = Console.ReadLine();

                    var message = new Message
                    {
                        Login   = _login,
                        Time    = DateTime.UtcNow.ToTimestamp(),
                        Content = messageContent ?? string.Empty
                    };

                    await chatService.SendAsync(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadKey();
            }

            CancellationTokenSource.Cancel();
        }
Esempio n. 8
0
        private void InitializeGrpc()
        {
            // Create a channel
            var channel = new Channel(Host + ":" + Port, ChannelCredentials.Insecure);

            // Create a client with the channel
            _chatService = new ChatService.ChatServiceClient(channel);
        }
 public ChatServiceClientWrapper
 (
     ChatService.ChatServiceClient chatServiceClient,
     ILogServiceFactory logServiceFactory
 )
     : base(logServiceFactory.CreateLogger <ChatServiceClientWrapper>())
 {
     _chatServiceClient = chatServiceClient;
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of <see cref="Connection"/>.
        /// </summary>
        /// <param name="channel">The <see cref="Channel"/> to be used for communication.</param>
        public Connection(Channel channel)
        {
            ExceptionHelper.ThrowIfNull(nameof(channel), channel);

            var client = new ChatService.ChatServiceClient(channel);

            _channel      = channel;
            _duplexStream = client.Subscribe();
            _subscription = ReadMessagesAsync(_tokenSource.Token);
        }
Esempio n. 11
0
        private void InitializeGrpc()
        {
            var channel = new Channel(Host + ":" + Port, ChannelCredentials.Insecure);

            // Create a client with the channel
            var chatService = new ChatService.ChatServiceClient(channel);

            // Open a connection to server
            _call = chatService.chat();
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     ChatService.ChatServiceClient chatService = new ChatService.ChatServiceClient();
     FileService.FileUpLoadServiceClient fileService = new FileService.FileUpLoadServiceClient();
       //  var id = Convert.ToInt32(Request.QueryString[ID]);
       //  string qs = Request.QueryString[ID];
     string param1 = Request.Url.ToString().Split('=')[1];
     int id = Convert.ToInt32(param1);
     Library.File hest = fileService.getFileById(id);
     List<ChatMessage> kat = chatService.GetLast20MessagesFromFile(hest).ToList();
     Repeater2.DataSource = kat;
     Repeater2.DataBind();
 }
Esempio n. 13
0
        private void Connect(string username, string host = "localhost", int port = 1337)
        {
            Debug.Print($"Client Connect: Username='******' Host='{host}' Port='{port}'");

            var channelOptions = new List <ChannelOption> {
                new ChannelOption("GRPC_ARG_KEEPALIVE_TIME_MS", 60 * 1000),
                new ChannelOption("GRPC_ARG_KEEPALIVE_TIMEOUT_MS", 5 * 1000),
                new ChannelOption("GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA", 0),
                new ChannelOption("GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS", 1)
            };

            channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure, channelOptions);

            client = new ChatService.ChatServiceClient(channel);

            var headers = new Metadata();

            headers.Add("username", username);

            try
            {
                call = client.ChatStream(headers);
                var responseHeaders = call.ResponseHeadersAsync.Result;

                if (responseHeaders.GetValue("status") != "OK")
                {
                    throw new Exception("Connection failed");
                }

                toolStripStatusLabel1.Text = "Connected";
                btnConnect.Enabled         = false;
                btnDisconnect.Enabled      = true;

                Task.Run(async() => await ProcessResponseStream()).ContinueWith(t =>
                {
                    if (t.Exception != null)
                    {
                        MessageBox.Show(t.Exception.Message, t.Exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    Disconnect();
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 14
0
        private static async Task Main(string[] args)
        {
            Console.Write("Please enter your name: ");
            var username = Console.ReadLine();

            Console.Write("Please enter number of the room: ");
            var room = Convert.ToInt32(Console.ReadLine());

            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new ChatService.ChatServiceClient(channel);

            using (var chat = client.Join())
            {
                _ = Task.Run(async() =>
                {
                    while (await chat.ResponseStream.MoveNext(CancellationToken))
                    {
                        var response = chat.ResponseStream.Current;
                        Console.WriteLine($"Room {response.Room} : {response.User} : {response.Text}");
                    }
                });

                await chat.RequestStream.WriteAsync(new Message
                                                    { Room = room, User = username, Text = $"{username} has joined the chat!" });

                string line;


                while ((line = Console.ReadLine()) != null)
                {
                    if (line.ToUpper() == "EXIT")
                    {
                        break;
                    }
                    Console.Clear();
                    client.ToDB(new Message {
                        Room = room, User = username, Text = line
                    });
                    await chat.RequestStream.WriteAsync(new Message { Room = room, User = username, Text = line });
                }

                await chat.RequestStream.CompleteAsync();
            }

            Console.WriteLine("Disconnection started!");
            await channel.ShutdownAsync();
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            ChatService.IChatService service = new ChatService.ChatServiceClient();

            Console.WriteLine("Loading messages...");

            String[] messages =  service.GetMessages();
            PrintMessages(messages);

            String line = Console.ReadLine();
            while(!line.Equals("exit")){
                messages = service.SendMessage(line);
                PrintMessages(messages);
                line = Console.ReadLine();

            }
        }
Esempio n. 16
0
        static async Task Main(string[] args)
        {
            Console.Write("Please enter your name: ");
            var username = Console.ReadLine();
            var channel  = GrpcChannel.ForAddress("https://localhost:5001");
            var client   = new ChatService.ChatServiceClient(channel);

            foreach (var chatRoom in client.GetChatRoomsAsync(new Lookup()).ResponseAsync.Result.ChatRooms_)
            {
                Console.WriteLine(chatRoom.Id + ": " + chatRoom.Name);
            }
            using (var chat = client.JoinAndWriteMessage())
            {
                Console.WriteLine("Enter id of chat room to join");
                string preferredChatRoom = Console.ReadLine();
                _ = Task.Run(async() =>
                {
                    while (await chat.ResponseStream.MoveNext())
                    {
                        var response = chat.ResponseStream.Current;
                        Console.WriteLine($"{response.User} : {response.Text}");
                    }
                });
                if (!string.IsNullOrEmpty(preferredChatRoom))
                {
                    Console.Clear();
                    await chat.RequestStream.WriteAsync(new Message { User = username, ChatRoomId = preferredChatRoom });
                }
                string messageText;
                while ((messageText = Console.ReadLine()) != null)
                {
                    if (messageText.ToUpper() == "EXIT")
                    {
                        break;
                    }
                    await chat.RequestStream.WriteAsync(new Message { User = username, Text = messageText, ChatRoomId = preferredChatRoom });
                }

                await chat.RequestStream.CompleteAsync();
            }

            Console.WriteLine("Disconnection started!");
            await channel.ShutdownAsync();
        }
Esempio n. 17
0
        static async Task Main(string[] args)
        {
            Console.Write("Please enter your name: ");
            var username = Console.ReadLine();

            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new ChatService.ChatServiceClient(channel);

            using (var chat = client.Join())
            {
                _ = Task.Run(async() =>
                {
                    while (await chat.ResponseStream.MoveNext())
                    {
                        var response = chat.ResponseStream.Current;
                        Console.WriteLine($"{response.User} : {response.Text}");
                    }
                }
                             );
            }
        }
Esempio n. 18
0
        static async Task Main()
        {
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new ChatService.ChatServiceClient(channel);

            // Enter name
            Console.Write("Enter user name to join chat: ");
            _userName = Console.ReadLine();

            // Create duplex chat rpc stream
            using var chatStream = client.Chat();

            // Wire up CallbackHandler to ResponseStream - print chant messages from service
            var callbackHandler = new CallbackHandler(chatStream.ResponseStream);

            // Send init-message to join the chat
            await chatStream.RequestStream.WriteAsync(new ChatMessage { User = _userName, Text = string.Empty });

            // Run input loop
            await InputLoop(chatStream);

            // Run callback loop
            await callbackHandler.Task;
        }
Esempio n. 19
0
        static async Task Main(string[] args)
        {
            try
            {
                Console.WriteLine("Starting service.");
                var channel           = new NamedPipeChannel(".", "Test");
                var chatServiceClient = new ChatService.ChatServiceClient(channel);

                Console.WriteLine("Press enter if your message is empty to abort the program.");
                while (true)
                {
                    Console.Write("You: ");
                    var content = Console.ReadLine();
                    if (string.IsNullOrEmpty(content))
                    {
                        return;
                    }

                    Console.WriteLine("Sending message ...");
                    var response = await chatServiceClient.SendMessageAsync(new ChatRequest()
                    {
                        Name = content
                    });

                    Console.WriteLine($"Received: {response.Message}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.ReadKey();
            }
        }
Esempio n. 20
0
        static async Task Main(string[] args)
        {
            Console.Write("Enter your name:");
            var username = Console.ReadLine();
            var channel  = GrpcChannel.ForAddress("https://localhost:5001");
            var client   = new ChatService.ChatServiceClient(channel);

            using (var chat = client.Join())
            {
                _ = Task.Run(async() =>
                {
                    while (await chat.ResponseStream.MoveNext())
                    {
                        var response = chat.ResponseStream.Current;
                        Console.WriteLine($"{response.User}:{response.Text}");
                    }
                });



                await chat.RequestStream.WriteAsync(new Message { User = username, Text = $"{username} has joined the chat" });

                string line;
                while ((line = Console.ReadLine()) != null)
                {
                    if (line.ToUpper() == "EXIT")
                    {
                        break;
                    }
                    await chat.RequestStream.WriteAsync(new Message { User = username, Text = line });
                }
                await chat.RequestStream.CompleteAsync();
            }
            Console.WriteLine("He(Her)is leaving");
            await channel.ShutdownAsync();
        }
Esempio n. 21
0
        static async Task Main(string[] args)
        {
            Console.Write("Please enter your name: ");
            var username = Console.ReadLine();

            var channel = GrpcChannel.ForAddress("http://localhost:5001");
            var client  = new ChatService.ChatServiceClient(channel);

            using (var chat = client.Join())
            {
                _ = Task.Run(async() =>
                {
                    while (await chat.ResponseStream.MoveNext(cancellationToken: CancellationToken.None))
                    {
                        var response = chat.ResponseStream.Current;
                        Console.WriteLine($"{response.User}: {response.Text}");
                    }
                });

                await chat.RequestStream.WriteAsync(new Message { User = username, Text = $"{username} has joined the room" });

                string line;
                while ((line = Console.ReadLine()) != null)
                {
                    if (line.ToLower() == "bye")
                    {
                        break;
                    }
                    await chat.RequestStream.WriteAsync(new Message { User = username, Text = line });
                }
                await chat.RequestStream.CompleteAsync();
            }

            Console.WriteLine("Disconnecting");
            await channel.ShutdownAsync();
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string host = "localhost";
            //host = "34.229.211.196";

            Channel channel = new Channel(host + ":32000", ChannelCredentials.Insecure);


            var id = new IdentityService.IdentityServiceClient(channel);

            Console.WriteLine("Key:");
            var k = Console.ReadLine();

            Console.WriteLine("Password:"******"Already exists.");
            }

            var authorization = id.ValidateIdentity(new ValidateIdentityRequest {
                Key = k, Passcode = v
            });

            Console.WriteLine(authorization);


            var client = new ChatService.ChatServiceClient(channel);

            Console.WriteLine("listening");
            using (var call = client.Listen(new ListenRequest()
            {
                SessionToken = Guid.NewGuid().ToString()
            }))
            {
                var receiverTask = Task.Run(async() =>
                {
                    while (await call.ResponseStream.MoveNext())
                    {
                        var message = call.ResponseStream.Current;
                        Console.WriteLine(message);
                    }
                });

                string newMessage;
                do
                {
                    newMessage = Console.ReadLine();
                    client.SendMessage(new SendMessageRequest {
                        Message      = newMessage,
                        SessionToken = authorization.SessionToken
                    });
                }while (!string.IsNullOrEmpty(newMessage));
            }

            // axicli identity login
            // axicli chat [channel] [message ...]

            channel.ShutdownAsync().Wait();
        }
Esempio n. 23
0
		static async Task Main(string[] args)
		{
			AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

			var channel = GrpcChannel.ForAddress("https://localhost:5001");
			var customerClient = new Customer.CustomerClient(channel);

			#region Unary RCP
			Console.WriteLine("Unary RPC");
			Console.WriteLine("==============================================");
			await EnterCustomerDetail(customerClient);

			Console.WriteLine("Would you like to get any customer detail ? y/n");
			bool isRpt = Convert.ToBoolean((Console.ReadLine().ToLower().Equals("y", StringComparison.InvariantCultureIgnoreCase)) ? true : false);

			if (isRpt)
			{
				await EnterCustomerDetail(customerClient);
			}
			#endregion

			#region Server Streaming RCP

			Console.WriteLine();
			Console.WriteLine("Server Streaming");
			Console.WriteLine("==============================================");
			Console.WriteLine();
			Console.WriteLine("All Customers List :");
			Console.WriteLine();
			using (var call = customerClient.GetNewCustomer(new NewCustomerRequest()))
			{
				while (await call.ResponseStream.MoveNext())
				{
					var currentCustomer = call.ResponseStream.Current;

					Console.WriteLine($"{currentCustomer.FirstName} {currentCustomer.LastName} :- {currentCustomer.EmailAddress}");
				}
			}
			#endregion

			#region Client Streaming RCP
			Console.WriteLine();
			Console.WriteLine("Client Streaming");
			Console.WriteLine("==============================================");


			var streamClient = new Cltstream.CltstreamClient(channel);
			await ClientStreamingCallExample(streamClient);

			#endregion

			#region Bidirectional RCP
			Console.WriteLine();
			Console.WriteLine("Bi-Direactional Streaming");
			Console.WriteLine("==============================================");

			var customer = new CustomerProtoModel
			{
				ColorInConsole = GetRandomChatColor(),
				Id = Guid.NewGuid().ToString(),
				Name = args.Length > 0 ? args[0] : "TheHulk"
			};


			var client = new ChatService.ChatServiceClient(channel);
			var joinCustomerReply = await client.JoinCustomerChatAsync(new JoinCustomerRequest
			{
				Customer = customer
			});

			using (var streaming = client.SendMessageToChatRoom(new Metadata { new Metadata.Entry("CustomerName", customer.Name) }))
			{
				var response = Task.Run(async () =>
				{
					while (await streaming.ResponseStream.MoveNext())
					{
						Console.ForegroundColor = Enum.Parse<ConsoleColor>(streaming.ResponseStream.Current.Color);
						Console.WriteLine($"{streaming.ResponseStream.Current.CustomerName}: {streaming.ResponseStream.Current.Message}");
						Console.ForegroundColor = Enum.Parse<ConsoleColor>(customer.ColorInConsole);
					}
				});

				await streaming.RequestStream.WriteAsync(new ChatMessage
				{
					CustomerId = customer.Id,
					Color = customer.ColorInConsole,
					Message = "",
					RoomId = joinCustomerReply.RoomId,
					CustomerName = customer.Name
				});
				Console.ForegroundColor = Enum.Parse<ConsoleColor>(customer.ColorInConsole);
				Console.WriteLine($"Joined the chat as {customer.Name}");

				var line = Console.ReadLine();
				DeletePrevConsoleLine();
				while (!string.Equals(line, "qw!", StringComparison.OrdinalIgnoreCase))
				{
					await streaming.RequestStream.WriteAsync(new ChatMessage
					{
						Color = customer.ColorInConsole,
						CustomerId = customer.Id,
						CustomerName = customer.Name,
						Message = line,
						RoomId = joinCustomerReply.RoomId
					});
					line = Console.ReadLine();
					DeletePrevConsoleLine();
				}
				await streaming.RequestStream.CompleteAsync();
			}
			Console.WriteLine("Press any key to exit...");
			#endregion


			Console.WriteLine("==========**** END ****===========");
			Console.ReadLine();
		}
Esempio n. 24
0
        public void Connect()
        {
            var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure);

            _client = new ChatService.ChatServiceClient(channel);
        }
Esempio n. 25
0
 /// <summary>
 /// Call Save User method.
 /// </summary>
 /// <param name="client">The client instance of ChatService.</param>
 /// <param name="nickname">The nickname information.</param>
 public void SaveUser(ChatServiceCallbackClient client, string nickname)
 {
     inst       = new InstanceContext(client);
     chatClient = new ChatService.ChatServiceClient(inst);
     chatClient.SaveUser(nickname);
 }