I am currently working on a c# program where I am opening a connection on a socket and listening for clients.
How can I check if the TcpListener has any clients currently connected. I want to do this so when someone closes the console application instead of it just terminating anything that is connect it will instead wait for all connected clients to finish before exiting the console app.
Below is the code:
TcpClient client = listener.AcceptTcpClient();
if (client.Connected)
{
library.logging(classDetails + MethodInfo.GetCurrentMethod().Name,
string.Format("Client Connected: {0}",((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString()));
NetworkStream stream = client.GetStream();
byte[] data = new byte[client.ReceiveBufferSize];
int bytesRead = stream.Read(data, 0, Convert.ToInt32(client.ReceiveBufferSize));
string request = Encoding.ASCII.GetString(data, 0, bytesRead);
byte[] msg = System.Text.Encoding.ASCII.GetBytes("200 OK");
ProcessXML process = new ProcessXML(library, appSettings);
// Send back a response.
stream.Write(msg, 0, msg.Length);
process.processXML(request, ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
client.Close();
Is there a method within the TcpListener to get a count of connected clients or has this got to be managed by myself by adding the client to something like a list array and then remove it when the client closes.
To the best of my knowledge, TcpListener does not internally keep track of accepted connections – that must be done explicitly by the application as needed.