salve a tutti
ho il seguente listener (codice in basso) (applicazione console)
che quando un client si connette alla porta 3001 del mio PC mi dice quando si connette e se invia un messaggio mi dice il messaggio in qeustione
il problema è che non capisco quando il client si disconnette, ed infatti si impalla in un ciclo infinito nella parte : while (client.Connected)
Ho aggiunto del codice che fa il ping nel ciclo, ma (strano ma vero) riporta false anche se è connesso
mi ci sto perdendo in questo codice!!
codice:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace ConsoleApp2 { class Program { static void Main(string[] args) { int port = 3001; TcpListener listener = new TcpListener(IPAddress.Any, port); listener.Start(); Console.WriteLine("Listening on port " + port + "..."); while (true) { TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Accepted connection from " + client.Client.RemoteEndPoint.ToString()); while (client.Connected) { NetworkStream stream = client.GetStream(); if (stream.DataAvailable) { byte[] buffer = new byte[1024]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string data = Encoding.UTF8.GetString(buffer, 0, bytesRead); Console.WriteLine("Received data: " + data); } //check if client still connected string[] cli = client.Client.RemoteEndPoint.ToString().Split(Convert.ToChar(":")); string Host = cli[0]; int Uri = port;// int.Parse(cli[1]); if (PingHost(Host,Uri)==false) { Console.WriteLine("Client disconnected."); break; } } } } public static bool PingHost(string hostUri, int portNumber) { try { using (var client = new TcpClient(hostUri, portNumber)) return true; } catch (SocketException ex) { //MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'"); return false; } } } }

Rispondi quotando