Exemple #1
0
        private void ReceiveMessage()
        {
            try
            {
                while (true)
                {
                    byte[] rawMessage = tcpClient.GetMessage();

                    string messageInJson = ParseMessageToJson(rawMessage, serverKey);

                    Message message = JsonSerializer.Deserialize <Message>(messageInJson);

                    if (message.MessageType == MessageType.Response)
                    {
                        Response response = JsonSerializer.Deserialize <Response>(messageInJson);

                        responseHandlers[response.RequestId].Invoke(messageInJson);
                        responseHandlers.Remove(response.RequestId);
                    }
                    else if (message.MessageType == MessageType.Notification)
                    {
                        NotificationHandler(messageInJson);
                    }
                }
            }
            catch (IOException)
            {
                Console.WriteLine("Connection is closed");
                Dispose();
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Error = {exception.Message}");
            }
        }
Exemple #2
0
        public void Process()
        {
            try
            {
                Console.WriteLine($"New connection - {Id}");

                Console.WriteLine($"Key exchange");
                KeyExchange();

                Console.WriteLine(
                    $"Key exchanged successfully. Connection configured. Id-{Id}; Key-{Convert.ToBase64String(aesEncryption.GetKey())}");

                while (true)
                {
                    byte[] rawMessage = tcpClient.GetMessage();

                    string messageInJson = ParseMessageToJson(rawMessage, ClientAesKey);

                    Request request = JsonSerializer.Deserialize <Request>(messageInJson);

                    Console.WriteLine($"{request.Sender} - {request.Action}");
                    RequestHandlers[request.Action].Invoke(messageInJson);
                }
            }
            catch (IOException)
            {
                Console.WriteLine($"User left. Username: {CurrentUserName}; id: {Id}");
                if (CurrentUserName != null)
                {
                    server.UserRepository.UpdateState(CurrentUserName, UserState.Offline);
                }

                server.RemoveConnection(this);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }