简体   繁体   中英

Check if TcpListener has any connected clients

I am currently working on ac# 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.

据我所知,TcpListener不会在内部跟踪接受的连接-必须由应用程序根据需要显式完成。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM