Transmission error socket c#

Asked

Viewed 39 times

1

I have the following code:

        public void StartListening()
    {

        try
        {
            btEngine = new Engine(true);

            IPAddress ip = IPAddress.Parse(txtServer.Text);
            IPEndPoint localEndPoint = new IPEndPoint(ip, 5000);

            Socket listener = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            listener.Bind(localEndPoint);
            listener.Listen(9000);
            newLine("Servidor iniciado no ip: " + ip.ToString());
            newLine("Aguardando pacote de impressão...");

            while (true)
            {
                allDone.Reset();

                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                allDone.WaitOne();
            }

        }
        catch (SocketException e)
        {
            MessageBox.Show(e.Message, "ERRO DE CONEXÃO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Debug.WriteLine(e);
        }
        catch (PrintEngineException e)
        {
            MessageBox.Show(e.Message, "ERRO NO BARTENDER", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Debug.WriteLine(e);
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message, "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            Debug.WriteLine(e);
        }
    }

    public void AcceptCallback(IAsyncResult ar)
    {
        allDone.Set();

        Socket listener = (Socket)ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        StateObject state = new StateObject();
        state.workSocket = handler;

        handler.BeginReceive(state.buffer, 0, handler.ReceiveBufferSize, 0, new AsyncCallback(ReadCallback), state);
    }

    public void ReadCallback(IAsyncResult ar)
    {
        string content = string.Empty;

        StateObject state = (StateObject)ar.AsyncState;
        Socket handler = state.workSocket;

        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));

            content = state.sb.ToString();
            Debug.WriteLine(content);
            Pessoa pessoa = JsonConvert.DeserializeObject<Pessoa>(content);
            newLine("Imprimindo etiqueta de " + pessoa.nome + " na impressora " + pessoa.impressora + "...");
            string modeloName = RemoverAcentos(pessoa.categoria.nome).Replace(" ", "_").ToUpper();
            if (modelos.ContainsKey(modeloName) || modelos.ContainsKey("PADRAO"))
            {
                LabelFormatDocument labelFormat = modelos.ContainsKey(modeloName) ? modelos[modeloName] : modelos["PADRAO"];
                pessoa.setSubstrings(labelFormat.SubStrings);
                labelFormat.PrintSetup.PrinterName = pessoa.impressora;
                var result = labelFormat.Print("ALFA CREDENCIAMENTO");
                switch (result.ToString())
                {
                    case "Success":
                        Send(handler, "Etiqueta impressa com sucesso!");
                        newLine("Etiqueta impressa com sucesso!");
                        break;
                    case "Failure":
                        Send(handler, "Erro ao imprimir etiqueta!");
                        newLine("Erro ao imprimir etiqueta!");
                        break;
                    default:
                        break;
                }
            }
            else notificar("Não há um modelo padrão para impressão", ToolTipIcon.Error);
        }
    }

    private void Send(Socket handler, String data)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket handler = (Socket)ar.AsyncState;

            int bytesSent = handler.EndSend(ar);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
    public class StateObject
    {
        public Socket workSocket = null;
        public const int BufferSize = 179200;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder sb = new StringBuilder();
    }

When performing the transmission of information the first time will right, already the second from now it loses some information, only receives 8k. I have tried in every way, changing the amount of bytes it receives but it always occurs the msm problem, I have done the test using a python server and the data are received correctly, so the problem is not in sending. Note, I accept suggestions for code improvement.

Edit: this only happens when there is more than 8k of information being transmitted, when there is less than no error.

  • For TCP connection have to adjust Bloking in false and call 'Connect

  • If solved, the solution should be posted in the form of an answer, not as an edit in the question.

  • Thanks for the help

1 answer

0

I decided to put a checker end of line, as follows...

if (content.IndexOf("\n") > -1)
            {
                Pessoa pessoa = JsonConvert.DeserializeObject<Pessoa>(content);
                newLine("Imprimindo etiqueta de " + pessoa.nome + " na impressora " + pessoa.impressora + "...");
                string modeloName = RemoverAcentos(pessoa.categoria.nome).Replace(" ", "_").ToUpper();
                if (modelos.ContainsKey(modeloName) || modelos.ContainsKey("PADRAO"))
                {
                    LabelFormatDocument labelFormat = modelos.ContainsKey(modeloName) ? modelos[modeloName] : modelos["PADRAO"];
                    pessoa.setSubstrings(labelFormat.SubStrings);
                    labelFormat.PrintSetup.PrinterName = pessoa.impressora;
                    var result = labelFormat.Print("ALFA CREDENCIAMENTO");
                    switch (result.ToString())
                    {
                        case "Success":
                            Send(handler, "Etiqueta impressa com sucesso!");
                            newLine("Etiqueta impressa com sucesso!");
                            break;
                        case "Failure":
                            Send(handler, "Erro ao imprimir etiqueta!");
                            newLine("Erro ao imprimir etiqueta!");
                            break;
                        default:
                            break;
                    }
                }
                else notificar("Não há um modelo padrão para impressão", ToolTipIcon.Error);
            }
            else
            {
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }

Browser other questions tagged

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