hi, i’m trying to establish a connection with a device via TCP/IP send some data and also recieve data, then close the connection.
After that, it would be able to connect with another device and do the same things.
Here is my code.
//global variables
static Socket ServidorTCPIP;
static IPEndPoint TCPEndpoint;
Here i make the connection and send the data, also start a thread for the incoming one.
ServidorTCPIP = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TCPEndpoint = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 23);
ServidorTCPIP.Connect(TCPEndpoint);
new Thread(LecturaTCP).Start();
ServidorTCPIP.Send(Encoding.UTF8.GetBytes("hello world\r\n"));
here the thread code
private void LecturaTCP()
{
while (true)
{
if (ServidorTCPIP.Poll(-1, SelectMode.SelectRead))
{
byte[] entrada = new byte[ServidorTCPIP.Available];
int cuenta = ServidorTCPIP.Receive(entrada);
char[] caracteres = Encoding.UTF8.GetChars(entrada);
string cadena = new string(caracteres, 0, cuenta);
respuesta = cadena;
}
}
}
All this works well but i’m having an exception of “no free sockets” when i try to close the current connection, i think it is maybe i have the thread running.
I’d like to have this thread running always and just close the current connection and open another one.