c# - 如何正确关闭或销毁TCP客户端?

标签 c# networking tcp unity3d

当客户端断开连接时,我在服务器上有以下代码:

更新内部,每帧运行:

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();

            }

        }

    }

现在,当我在那之后尝试调试时,仍然在 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]);

    }

这部分是从 disconnectedClients 列表中删除断开连接的客户端,但是当我运行它并退出客户端时,这是 Unity 在控制台中抛出的内容,只是一个片段:

enter image description here

它还在继续。所以一个 - for 循环 不会停止,这意味着客户端会不断添加到列表中,对吗?现在出了什么问题,如何正确删除(关闭)客户端

在客户端我运行:

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

仅供引用,类 ClientEntity:

public class ClientEntity {

  public TcpClient tcpClient;
  public string tcpClientName;

  public ClientEntity(TcpClient tcpClientSocket){

      tcpClientName = "Guest";
      tcpClient = tcpClientSocket;

  }
}

最佳答案

TcpClient.Close 方法在您的情况下工作正常。但是,您没有在客户端断开连接后从 connectedClients 列表/数组中删除客户端,这导致 if !isClientStillConnected(client.tcpClient)) 语句再次评估为 true .像这样更改您的代码:

//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);
}

关于c# - 如何正确关闭或销毁TCP客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024658/

相关文章:

c++ - 使用 Qt 下载文件?

使用 Select() 的 Linux TCP 连接在测试服务器上失败

java - 在 Java 中创建网络数据包层次结构

Java 多线程服务器与各个客户端通信,但不同时与所有客户端通信

c++ - 我可以延长接受服务器的 TCP 握手持续时间吗?

perl - 如何检查哪种检查端口状态的方法更有效?

Java Base64.getDecoder().decode() C# 等效项

c# - 我想将我的分钟、秒和百分之一拆分为秒和百分之一

c# - AWS Lambda/API 网关上的文件编码问题

c# - 获得更高的使用位位置