new public static void Handle(string data, Connection connection) { Message message = RequestConverter.DecomposeMessage(data); message.SendedTime = DateTime.UtcNow; try { MessageService.SaveMessageIfLocalIdUnique(message); message = MessageService.GetMessageById(message.Id); Package.Write( connection.TcpClient.GetStream(), RequestConverter.ComposeMessageSyncInfo(message.Id, message.SenderLocalId, message.SendedTime)); Connection receiverConnection = ConnectionController.Connections .FirstOrDefault(c => c.ConnectedUser.Name == message.Receiver); if (!(receiverConnection is null)) { Package.Write( receiverConnection.TcpClient.GetStream(), RequestConverter.ComposeMessage(message)); } } catch (Exception ex) { if (ex is NullReferenceException || ex is InvalidOperationException) { //MessageService.SaveMessage(message); // here i got exception; i must correct it; //else //throw; Console.WriteLine(ex.Message); } } }
public async void Start() { await Task.Run(() => { try { TcpClient = new TcpClient(Constants.IP, Constants.PORT); NetworkStream ns = TcpClient.GetStream(); string buff; while (true) { while (ns.DataAvailable) { string receivedPackage = Package.Read(ns); RequestType type = RequestConverter.GetRequestType(receivedPackage); string data = RequestConverter.GetData(receivedPackage); switch (type) { case RequestType.LoginResponse: userHandler.Found = RequestConverter.DecomposeLoginResponse(data); break; case RequestType.RegistrationResponse: userHandler.Found = RequestConverter.DecomposeLoginResponse(data); break; case RequestType.SendMessage: Message message = RequestConverter.DecomposeMessage(data); messageHandler.SaveAndShowMessage(new LocalMessage(message)); Package.Write(ns, RequestConverter.ComposeMessageReceived(message.Id)); break; case RequestType.CheckUserExistResponse: userHandler.ReceiverFound = RequestConverter.DecomposeUserExistResponse(data); break; case RequestType.MessageSyncInfo: messageHandler.SyncMessage(RequestConverter.DecomposeMessageSyncInfo(data)); break; default: break; } } while (!RequestsToSend.IsEmpty) { RequestsToSend.TryTake(out buff); Package.Write(ns, buff); } Thread.Sleep(5); } } catch (IOException ioEx) { Console.WriteLine(ioEx.Message); } finally { TcpClient?.GetStream().Close(); TcpClient?.Close(); } }); }