Buenas a todos,
Ando haciendo un servicio para windows con C# que espera conexiones de formularios a traves de sockets y lanzo hilos en el servicio por cada cliente que conecta.
El problema que tengo es que cuando desconecto a un cliente, el servicio se para y deja sin conexion al resto de clientes, o si solo tengo un cliente conectado y se desconecta, el servicio ya no acepta mas conexiones. Os pego el codigo que es bastante conciso para ver si me podeis echar una manilla
El servicio ejecuta en OnStart()
Código:
this.tcpListener = new TcpListener(ipEnd);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
Código:
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
Código:
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
Cuando desconecto el cliente, el hilo se cierra correctamente por el "if (bytesRead == 0)" y despues ejecutando "tcpClient.Close()"
¿Porque si un unico thread se cierra el resto de hilos "desaparecen"
Muchas gracias por cualquier aportacion