Communicate ASP.NET with Windows Forms

Asked

Viewed 157 times

2

The problem is the following, I work with SAT-CFE and the 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 communicates with the SAT hardware and communicates with the ASP.NET system, I did this using Socket. It works. But there is a problem when the XML I send via socket is larger than 6kb it arrives incomplete and will not at all.

I’ve already increased buffer, I did everything and got nowhere. 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 some other better way to do this communication between a Web Application with a Desktop Local Application. I’m grateful for all your help.

1 answer

1


  • 1

    Thank you very much, Nice examples I will study their implementation in my project..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.