Micard
Micard

Reputation: 389

How to close or dispose of TCP client properly?

I have the following code on the server when the client disconnects:

Inside of Update, which runs every frame:

foreach (ClientEntity client in connectedClients) {

        if (!isClientStillConnected(client.tcpClient)) {

            disconnectedClients.Add(client);
            client.tcpClient.Close();
            Debug.Log (" :: Client " + client.tcpClientName + " has disconnected! ::");
            continue;

        } else {

            Do_The_Stuff_And_Things();

            }

        }

    }

Now when I try and debug right after that, still inside of the Update():

for (int i = 0; i < disconnectedClients.Count; i++) {

        Debug.Log(":: Disconnected clients count: " + disconnectedClients.Count.ToString());
        Debug.Log(":: Disconnected client at index " + i + ": " + disconnectedClients[i]);

    }

This section is to remove disconnected clients from the disconnectedClients list, but when I run it and quit the client, here's what Unity throws in the console, just a snippet:

enter image description here

And it goes on. So one - the for loop doesn't stop, which means the client is being constantly added to the list, right? Now what's wrong, how can I remove (close) the client properly?

On the client side I run:

        nwReader.Close ();
        nwWriter.Close ();
        tcpClient.Close ();
        socketReady = false;

Just FYI, class ClientEntity:

public class ClientEntity {

  public TcpClient tcpClient;
  public string tcpClientName;

  public ClientEntity(TcpClient tcpClientSocket){

      tcpClientName = "Guest";
      tcpClient = tcpClientSocket;

  }
}

Upvotes: 1

Views: 1548

Answers (1)

Koja
Koja

Reputation: 920

The TcpClient.Close method is working correctly in your case. However, you are not removing the client from the connectedClients List/Array after it disconnects, which results in the if !isClientStillConnected(client.tcpClient)) statement evaluating to true again. Change your code like this:

//This loop is unchanged
foreach (ClientEntity client in connectedClients)
{
    if (!isClientStillConnected(client.tcpClient)) {

        disconnectedClients.Add(client);
        client.tcpClient.Close();
        Debug.Log (" :: Client " + client.tcpClientName + " has disconnected! ::");
        continue;

    } else {

        Do_The_Stuff_And_Things();

        }

    }

}

//Remove all disconnected clients from the list of connected clients
foreach (var disconnectedClient in disconnectedClients)
{
    connectedClients.Remove(disconnectedClient);
}

Upvotes: 1

Related Questions