The discarded object can not be accessed. Object name: 'System.Net.Sockets.Socket'

3

I have been dealing with a problem for many days that I can not solve, I hope that a charitable soul will discover the error. I am using sockets to send messages and receive them from a server, the fact is that when I try to open the socket a second time it gives me the following exception:

  

The discarded object can not be accessed. Name of the object:   'System.Net.Sockets.Socket'.

The code is the following, the line where I stop the program with the exception is:

Socket envio = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Complete code:

#region TCP CLIENTE
// INICIALIZAR PROCEDIMIENTO
public void INITCPCliente()
{
    btntcpASocket.Enabled = true;
    btntcpCSocket.Enabled = false;
    btnTCPCEnviar.Enabled = false;
    txttcpResultados.ScrollBars = ScrollBars.Vertical;
}
// BOTON ABRIR SOCKET
public void btntcpASocket_Click(object sender, EventArgs e)
{
    hiloTCPCliente = new Thread (tcpCliente);
    hiloTCPCliente.Start();
}

Socket envio = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public void tcpCliente()
{
    actualizarUI("Intentando conectar a " + txttcpIP.Text + " : " + txttcpPuerto.Text);
    try
    {
        envio.Connect(IPAddress.Parse(txttcpIP.Text), Convert.ToInt16(txttcpPuerto.Text));
        if (envio.Connected)
        {
            btntcpASocket.Enabled = false;
            btnTCPCEnviar.Enabled = true;
            btntcpCSocket.Enabled = true;
            actualizarUI("Conectado");
        }
        else
        {
            actualizarUI("No se pudo conectar...");
        }
    }
    catch (Exception error)
    {
        actualizarUI(error.Message);
    }
}

// BOTON CERRAR SOCKET
private void btntcpCSocket_Click(object sender, EventArgs e)
{
    envio.Shutdown(SocketShutdown.Both);
    envio.Close();

    if (!envio.Connected)
    {
        btntcpASocket.Enabled = true;
        btnTCPCEnviar.Enabled = false;
        btntcpCSocket.Enabled = false;
        actualizarUI("Desconectado");
    }           
}

// BOTON ENVIAR TRAMA
private void btnTCPCEnviar_Click(object sender, EventArgs e)
{

    Thread hilo = new Thread(EnvioRecibo);
    hilo.Start();
}

private void EnvioRecibo()
{
    try
    {
        //Buffer de datos de servidor
        byte[] bytes = new byte[1024];
        //Envio de datos a servidor
        byte[] mensaje = Encoding.ASCII.GetBytes(txtASCII.Text);
        actualizarUI("Edu Tool -> " + txtASCII.Text);
        int bytesSent = envio.Send(mensaje);
        txtTCPCEnviados.Text = ("Bytes enviados : " + Convert.ToString(mensaje.Length));
        //Recibir datos de servidor
        int bytesRecibidos = envio.Receive(bytes);
        actualizarUI("Servidor <- " + Encoding.ASCII.GetString(bytes, 0, bytesRecibidos));
        txtTCPCRecibidos.Text = ("Bytes recibidos : " + bytesRecibidos);
    }
    catch (Exception)
    {
        actualizarUI("El servidor no devolvio ningun dato...");
    }
}

// MESANJES EN TCP CLIENTE
public void actualizarUI(string s)
{
    Func<int> del = delegate ()
    {
        txttcpResultados.AppendText(s + Environment.NewLine);
        return 0;
    };
    Invoke(del);
}

I think I explained myself wrong ... The code works, I even open the socket (instantiating the object) command telegrams and I receive them, and I close it ... With the method "envío.Close (). The problem is that when I try to open it again, if I try to instantiate "send" again, after having closed it, I skip that exception. I do not know how to operate since if I closed it I should be able to open it again, but I do not know how ...

    
asked by Edulon 08.06.2017 в 22:49
source

1 answer

0

If you throw the process in a separate Thread, you could close and delete the variables when finished, from the thread itself.

You can also try not to run on a separate thread to debug more easily.

Before assigning and closing check the assigned value.

Example of thread treatment

    
answered by 12.03.2018 в 11:24