Pregunta

Estoy intentando leer la respuesta de texto ASCII desde un socket de transmisión abierto TCP

Esto es lo que se me ocurrió hasta ahora.Quiero saber cuál es la mejor manera de hacer esto que incluya el manejo de errores.¿También debería verificar el SocketError después de la llamada de recepción en el bucle do?

IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 9000);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.SendTimeout = 5000;
sock.ReceiveTimeout = 5000;
if (null != sock)
{
    try
    {
        sock.Connect(ep);
        if (sock.Connected)
        {

            // Blocks until send returns.
            int bytesSent = sock.Send(buffer);
            Console.WriteLine("Sent {0} bytes.", bytesSent);
            //get the first 4 bytes, should be the lenngth of the rest of the response.
            byte[] response = new byte[4];
            int bytesRec = sock.Receive(response);
            int totalBytesRec = 0;
            if (4 == bytesRec)
            {
                int len = BitConverter.ToInt32(response, 0);
                response = new byte[len];
                Console.WriteLine("Trying to get {0} bytes.", len);
                bytesRec = 0;

                do
                {
                    bytesRec = sock.Receive(response);
                    totalBytesRec += bytesRec;
                    forecast += Encoding.ASCII.GetString(response, 0, bytesRec);
                } while (totalBytesRec < len && bytesRec > 0);

                if (totalBytesRec != len)
                    throw new Exception("The total bytes recieved from manager did not equal the expected bytes");
            }
            else
                throw new Exception("Unable to get the response size from the manager");


            Console.WriteLine("Received {0} bytes.", totalBytesRec);
        }

    }
    catch (SocketException ex)
    {
        Console.WriteLine("{0} Error code: {1}.", ex.Message, ex.ErrorCode);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        sock.Shutdown(SocketShutdown.Both);
        sock.Close();
    }
}
¿Fue útil?

Solución

Probablemente su mejor opción sea TcpClient.Hay un excelente ejemplo que hace exactamente lo que usted está haciendo en la documentación de .NET aquí:

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

¡Buena suerte para ti!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top