Communicate ASP.NET with Windows Forms

The problem is as follows, I work with SAT-CFe and communication with this is done via USB which makes it impossible for my web system to do direct communication with it.

What I did, I created a desktop application that does this communication with the SAT Hardware and communicates with the system ASP.NET, I did this using Socket. Work. But it has a problem when the XML that I send via socket is greater than 6kb it arrives incomplete and does not go at all.

Already I increased buffer, did everything and did not get anywhere. I will post the client and server methods:

Client:

   //Mensagem de Retorno Servidor em Byte
       byte[] retornoServidorByte = new byte[1024 * 5000];
       // byte[] retornoServidorByte = new byte[10485760];
        //Tenta enviar o arquivo ao cliente
        try
        {
            //Cria o IpEnd que sera o destino .. Este é atribuido o valor real abaixo
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 0);


                IPAddress ip = IPAddress.Parse(Auxiliares.sipRealCliente);
                ipEnd = new IPEndPoint(ip, 5859);

            //Cria o Socket
            Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            //Convert em Bit o xml a ser enviado ao cliente
            byte[] clientData = Encoding.UTF8.GetBytes(xml);

            try
            {
                //Coneta com o Cliente
                clientSock.Connect(ipEnd);
                //Envia os dados
                clientSock.Send(clientData);
                //Recebe o retorno do Servidor
                clientSock.Receive(retornoServidorByte);
            }
            catch (SocketException soc)
            {
                return soc.Message;
            }



            clientSock.Close();//Fecha a conexao com o Cliente

            //Monta o retorno em String
            return Encoding.UTF8.GetString(retornoServidorByte);

        }
        catch (Exception ex)
        {
            return ex.Message;
        }

Server:

 try
        {
            //Classes
            Sat sat = new Sat();
            Config config = new Config();


            WriteLog("Iniciando servidor...");

            //Cria o Ip que subira o servidor
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.None, 0000);
            //Verifica se usara ipLocal automatico ou o Ip configurado
            if (config.ConfigAutomatica == true)
            {
                ipEnd = new IPEndPoint(IPAddress.Parse(Config.GetIp()), 5859);
            }
            else
            {
                ipEnd = new IPEndPoint(IPAddress.Parse(config.Ip), config.Porta);
            }

            //Cria o SOCK
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            //Especifica ao Sock qual Ip Sera usadao
            sock.Bind(ipEnd);

            //Começa Ouvir no maximo 100 Solicitaçoes
            sock.Listen(100);

            WriteLog("Servidor iniciado e escutando em: " + ipEnd.Address + ":" + ipEnd.Port);
            WriteLog("Aguardando nova conexao cliente...");

            Thread listen = new Thread(() =>
            {
                while (true)
                {

                    //Aceita a conexao
                    using (Socket clientSock = sock.Accept())
                    {

                        WriteLog("Cliente: " + clientSock.RemoteEndPoint + " Conectado");

                        //Cria uma Thread
                        //var threadData = new Thread(() =>
                        //{
                        //Armazena o retorno vindo do cliente
                       byte[] clientData = new byte[1024*5000];
                     //   byte[] clientData = new byte[10485760];
                        //Recebe os arquivos do Cliente
                      int k = clientSock.Receive(clientData);

                        WriteLog("Recebendo dados cliente...");


                        //Converte o valor vindo do servidor para string
                        string xml = Encoding.UTF8.GetString(clientData).Replace("\0", string.Empty);

                        //Troca a codificação do XML para UTF-8
                        xml = xml.Replace("utf-16", "utf-8");

                        WriteLog("Arquivo Recebido com sucesso!!");
                        var retorno = "Recebido com Sucesso!";

                        //Pega o retorno do SAT e envia devolta ao cliente
                        byte[] arquivoRetorno = Encoding.UTF8.GetBytes(retorno);
                        clientSock.Send(arquivoRetorno);

                        //Fecha a conexao
                        clientSock.Close();

                        WriteLog(System.Environment.NewLine);
                        WriteLog("Aguardando nova conexao cliente...");
                        //});
                        //threadData.Start(); //Inicia novamente a Thread
                    }
                }
            });
            listen.IsBackground = true;
            listen.Name = "Servidor";
            listen.Start();
        }
        catch (Exception ex)
        {
            Config.GravarLog(Types.TipoLog.Erro, ex, "");
            WriteLog("Ocorreu uma falha: " + ex.Message);
        }

I would like to know what I can do with the code to fix this, or if there is any other better way to do this communication between a Web application and a local Desktop application. I'm grateful for everyone's help.

Author: Taisbevalle, 2016-09-30

1 answers

Socket is not the best way to do this communication between systems by sending files. For end-to-end short messages, it is valid. The best in the case, is you work with a WCF service that will accomplish this cool task.

In the two links below, you can make a short download of a demo that can help you in this:

  1. https://code.msdn.microsoft.com/windowsdesktop/Upload-files-using-a-REST-13f16af2
  2. http://www.codeproject.com/Articles/166763/WCF-Streaming-Upload-Download-Files-Over-HTTP

Good luck!

 1
Author: Rodrigo Kono, 2016-10-01 04:13:42