public async Task <bool> Enviar_Receber_ArquivoAsync(Pacote_File Pacote, ProgressBar Progresso = null) { try { Pacote.ReceiveBufferCLiente = ClientToServer.ReceiveBufferSize; //Envia para o server a capacidade de recepção Pacote.SendBufferCliente = ClientToServer.SendBufferSize; //envia para o server capacidade o tamanho de envio; int ReceiveBufferClienteSize = ClientToServer.ReceiveBufferSize; //Envia para o server a capacidade de recepção int SendBufferClienteSize = ClientToServer.SendBufferSize; //envia para o server capacidade o tamanho de envio; string Dados = SerializarPacote(Pacote); BarramentoEscrita.WriteLine(Dados); BarramentoEscrita.Flush(); string DadosLidos = await BarramentoLeitura.ReadLineAsync(); Pacote_File PCT = DeserializarPacote(DadosLidos); int TamanhoArquivo = (int)PCT.Lenght; int ReceiveBufferServerSize = PCT.ReceiveBufferServidor; //Armazena o tamanho do buffer de recepção do cliente; int SendBufferServerSize = PCT.SendBufferServidor; //Armazena o tamanho do buffer de envio do cliente; int BufferRecepcao = ReceiveBufferClienteSize > SendBufferServerSize ? SendBufferServerSize : ReceiveBufferClienteSize; if (PCT.Existe) { byte[] Arquivo = new byte[BufferRecepcao]; using (BinaryReader RFile = new BinaryReader(ClientToServer.GetStream())) { using (FileStream Gravar = new FileStream(PCT.Destino, FileMode.Create)) { int LoopRecepcao = 0; do { int TotalRecebido = RFile.Read(Arquivo, 0, BufferRecepcao); Gravar.Write(Arquivo, 0, TotalRecebido); LoopRecepcao += TotalRecebido; Progresso.Value = (LoopRecepcao / TamanhoArquivo) * 100; } while (LoopRecepcao <= TamanhoArquivo); Gravar.Close(); } } } return(false); } catch (Exception e) { TratadorErros(e, this.GetType().Name); return(false); } }
/** * Data: 02/04/2019 * Transforma uma string em pacote para acesso. * Return: string */ private dynamic DeserializarPacote(string Pacote) { try { Base = JsonConvert.DeserializeObject <Pacote_Base>(Pacote); switch (Base.Pacote) { case TipoPacote.Auth: Pacote_Auth Auth = JsonConvert.DeserializeObject <Pacote_Auth>(Base.Conteudo); return(Auth); case TipoPacote.Comando: Pacote_Comando Exec = JsonConvert.DeserializeObject <Pacote_Comando>(Base.Conteudo); return(Exec); case TipoPacote.File: Pacote_File File = JsonConvert.DeserializeObject <Pacote_File>(Base.Conteudo); return(File); case TipoPacote.FileSystem: Pacote_SystemFile FileSystem = JsonConvert.DeserializeObject <Pacote_SystemFile>(Base.Conteudo); return(FileSystem); case TipoPacote.Echo: Pacote_PingEcho Ping = JsonConvert.DeserializeObject <Pacote_PingEcho>(Base.Conteudo); return(Ping); case TipoPacote.Replay: Pacote_PingReplay Replay = JsonConvert.DeserializeObject <Pacote_PingReplay>(Base.Conteudo); return(Replay); case TipoPacote.Inicializacao: Pacote_Inicializacao Inicializacao = JsonConvert.DeserializeObject <Pacote_Inicializacao>(Base.Conteudo); return(Inicializacao); default: throw new Exception("Tentativa de envio de pacote não reconhecida pelo sistema."); } } catch (Exception e) { TratadorErros(e, this.GetType().Name);; return(false); } }
/** * <summary> * Converte uma string em uma classe de pacote. * </summary> */ private dynamic DeserializarPacote(string Pacote) { Pacote_Base Base = JsonConvert.DeserializeObject <Pacote_Base>(Pacote); switch (Base.Pacote) { case TipoPacote.Auth: Pacote_Auth Auth = JsonConvert.DeserializeObject <Pacote_Auth>(Base.Conteudo); return(Auth); case TipoPacote.Comando: Pacote_Comando Exec = JsonConvert.DeserializeObject <Pacote_Comando>(Base.Conteudo); return(Exec); case TipoPacote.File: Pacote_File File = JsonConvert.DeserializeObject <Pacote_File>(Base.Conteudo); return(File); case TipoPacote.FileSystem: Pacote_SystemFile FileSystem = JsonConvert.DeserializeObject <Pacote_SystemFile>(Base.Conteudo); return(FileSystem); case TipoPacote.Echo: Pacote_PingEcho Ping = JsonConvert.DeserializeObject <Pacote_PingEcho>(Base.Conteudo); return(Ping); case TipoPacote.Replay: Pacote_PingReplay Replay = JsonConvert.DeserializeObject <Pacote_PingReplay>(Base.Conteudo); return(Replay); case TipoPacote.Inicializacao: Pacote_Inicializacao Inicializacao = JsonConvert.DeserializeObject <Pacote_Inicializacao>(Base.Conteudo); return(Inicializacao); } return(null); }
/** * Data: 27/02/2019 * Método que cria os barramentos de leitura e escrita, dá início ao diálogo inicial com os clientes e * e dá início à conversa contínua com os cliente. * Return: void */ private void Receber_Dados_Responder(object Dados) { StreamReader BarramentoLeitura; StreamWriter BarramentoEscrita; Pacote_Error P_Error; try { TcpClient Clients = (TcpClient)Dados; Func <string, bool> Falha = (G) => { if (G == null) { EndPoint Fl = Clients.Client.RemoteEndPoint; throw new Exception("Ocorreu uma falha no Servidor: " + Fl.ToString()); } else { return(true); } }; using (NetworkStream Brrm = Clients.GetStream()) { //Barramento de Leitura, após a abertura do socket BarramentoLeitura = new StreamReader(Brrm); //Obtém o Barramento de escrita com a cliente BarramentoEscrita = new StreamWriter(Brrm); string DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. Pacote_PingEcho Echo = DeserializarPacote(DadosLidos); /*Verifica se, cliente e servidor estão em sintonia, ocorreu algum erro*/ if (Echo.GetTipoPacote() != TipoPacote.Echo) { Pacote_PingReplay Replay = new Pacote_PingReplay(); Replay.Validado = false; Replay.ObterTempo(); /*Confirma o recebimento, do cliente, inicialização.*/ BarramentoEscrita.WriteLine(SerializarPacote(Replay)); BarramentoEscrita.Flush(); throw new Exception("Falha de comunicação inicial: Cliente"); } else { Pacote_PingReplay Replay = new Pacote_PingReplay(); Replay.Validado = true; Replay.ObterTempo(); /*Confirma o recebimento, do cliente, inicialização.*/ BarramentoEscrita.WriteLine(SerializarPacote(Replay)); BarramentoEscrita.Flush(); } DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. string EnviarDadosCliente = TratarInicializacao(DadosLidos); /*Informa ao cliente que os parâmetros de inicialização foram recebidos com sucesso.*/ BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); /*Processo de leitura do pacote de autenticação.*/ DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos); //Verifica se o barramento é nulo, caracterizando uma falha na comunicação. Pacote_Auth PTC = DeserializarPacote(DadosLidos); //Transforma string em um objeto da classe Pacote_Auth PTC.TEndPointServer = TEndPoint; PTC.DominioServidor = EDominio; Pacote_Auth _Autenticado = _Auth?.AutenticarUsuario(PTC); if (_Autenticado != null) { _GerenciadorCliente?.ConectarCliente(Clients.Client.RemoteEndPoint, _Autenticado); EnviarDadosCliente = SerializarPacote(_Autenticado); BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); //Leitura do barramento de dados do próximo tipo de pacote DadosLidos = BarramentoLeitura.ReadLine(); Falha(DadosLidos);//Verifica se o barramento é nulo, caracterizando uma falha na comunicação. dynamic QTP = DeserializarPacote(DadosLidos); switch (Base.Pacote) { case TipoPacote.Comando: Pacote_Comando CMM = (Pacote_Comando)QTP; //Transforma string em um objeto da classe Pacote_Auth string Executar = _ResponderRequisicao(CMM); if (Excecao) { P_Error = new Pacote_Error(); P_Error.Error = Excecao; P_Error.Mensagem = DadosExcecao.Message; P_Error.Tracer = DadosExcecao.StackTrace; Executar = SerializarPacote(P_Error); Excecao = false; DadosExcecao = null; } Pacote_Comando PCT = new Pacote_Comando(); PCT.Resposta = Executar; string DadosPacote = SerializarPacote(PCT); //Obtém o Barramento de escrita com a cliente BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); break; case TipoPacote.Echo: Pacote_PingReplay RPY = new Pacote_PingReplay(); DadosPacote = SerializarPacote(RPY); //Obtém o Barramento de escrita com a cliente BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); break; case TipoPacote.File: Pacote_File FILE = (Pacote_File)QTP; string PathFile = FILE.Path; int ReceiveBufferClienteSize = FILE.ReceiveBufferCLiente; //Armazena o tamanho do buffer de recepção do cliente; int SendBufferClienteSize = FILE.SendBufferCliente; //Armazena o tamanho do buffer de envio do cliente; int ReceiveBufferServerSize = Clients.ReceiveBufferSize; //Armazena o tamanho do buffer de recepção do cliente; int SendBufferServerSize = Clients.SendBufferSize; //Armazena o tamanho do buffer de envio do cliente; //Enviando dados dos buffers do servidor FILE.ReceiveBufferServidor = ReceiveBufferServerSize; //Envia para o server a capacidade de recepção FILE.SendBufferServidor = SendBufferServerSize; //envia para o server capacidade o tamanho de envio; int BufferTransmissao = ReceiveBufferClienteSize > SendBufferServerSize ? SendBufferServerSize : ReceiveBufferClienteSize; FILE.Existe = File.Exists(PathFile); if (FILE.Existe) { using (FileStream EnviarArquivo = new FileStream(FILE.Path, FileMode.Open)) { long TamanhoArquivoEnviar = EnviarArquivo.Length; FILE.Lenght = TamanhoArquivoEnviar; DadosPacote = SerializarPacote(FILE); BarramentoEscrita.WriteLine(DadosPacote); BarramentoEscrita.Flush(); byte[] T = new byte[BufferTransmissao]; using (BinaryWriter EVFILE = new BinaryWriter(Brrm)) { int LoopEnvio = 0; do { int TotalEnviado = EnviarArquivo.Read(T, 0, BufferTransmissao); EVFILE.Write(T); LoopEnvio += TotalEnviado; } while (LoopEnvio <= TamanhoArquivoEnviar); EnviarArquivo.Close(); } } } else { } break; default: P_Error = new Pacote_Error(); P_Error.Error = true; P_Error.Mensagem = "Esse tipo de pacote não existe."; P_Error.Tracer = ""; BarramentoEscrita.WriteLine(SerializarPacote(P_Error)); BarramentoEscrita.Flush(); break; } } else { //Não existe mecanismo de autenticação. _Autenticado = new Pacote_Auth { Autenticado = false, Error = true, EMensagem = "O servidor não está configurado com nenhum processo de autenticação." }; EnviarDadosCliente = SerializarPacote(_Autenticado); BarramentoEscrita.WriteLine(EnviarDadosCliente); BarramentoEscrita.Flush(); } BarramentoLeitura.Close(); BarramentoEscrita.Close(); //Desconectar_Cliente("10.56.34.222","80"); Clients.Close(); } } catch (Exception e) { TratadorErros(e, this.GetType().Name);; } }