TCP 客户端停止,直到被服务器断开连接

TCP Client stalled until disconnected by the server

当尝试通过 TCP 接收字符串或文件内容(作为字符串)时,我遇到了一个问题,即接收工作正常,但是行

print("TCP -> Data received:\n" + file + "\n\n" + totalrecbytes + " Bytes");

有点停滞,直到我主动断开与服务器端的连接。比预期的要好。

我调试接收里面的数据

while ((recBytes = netstream.Read(bytes, 0, bytes.Length)) > 0)

循环工作正常。它还会在正确的时刻结束循环。 但是在那之后什么也没有发生。我没有得到任何错误,不是 "trapped" 在任何循环中,但也没有得到

的预期输出
print("TCP -> Data received:\n" + file + "\n\n" + totalrecbytes + " Bytes");

直到我与服务器端断开连接。比我看到预期的输出和客户端断开连接。

这里是实现(原文source

private Thread _tcpThread;
private TcpClient _socketConnection;

public void Connect()
{
    try
    {
        _tcpThread = new Thread(ReciveDataClient);
        _tcpThread.IsBackground = true;
        _tcpThread.Start();
    }
    catch (Exception e)
    {
        print(e.Message);
    }
}

private void ReciveDataClient()
{
    try
    {
        _socketConnection = new TcpClient("xxx.xxx.xxx.xxx", 54321);
        print(this, "TCP -> Connection Success!");
    }
    catch (Exception e)
    {
        print("connection error: " + e.Message)
        return;
    }

    try
    {
        var bytes = new byte[BUFFER_SIZE];

        while (_socketConnection.Connected)
        {
            if (_socketConnection.Available <= 0) continue;

            // Get a stream object for reading              
            var netstream = _socketConnection.GetStream();

            int totalrecbytes = 0;

            int recBytes;
            string file = "";

            // Read incomming stream into byte arrary.                  
            while ((recBytes = netstream.Read(bytes, 0, bytes.Length)) > 0)
            {
                var incommingData = new byte[recBytes];
                Array.Copy(bytes, 0, incommingData, 0, recBytes);
                // Convert byte array to string message.                        
                var serverMessage = Encoding.ASCII.GetString(incommingData);
                file += serverMessage;
                totalrecbytes += recBytes;
            }

            print("TCP -> Data received:\n" + file + "\n\n" + totalrecbytes + " Bytes");

            netstream.Close();
        }

        print("TCP -> connection was terminated by the server");
    }
    catch (Exception e)
    {
        print(e.Message)
        return;
    }
}

我希望我可以保持连接有效,但仍能正确接收数据并在持久的 TCP 连接上与服务器通信。

我在这里遗漏了什么或做错了什么?


到目前为止我能找到的唯一解决方法是在发送数据后始终与服务器端断开连接,并且在我的代码中将整个 ReceiveDataClient 包装在一个 while 循环中,如

private void ReciveDataClient()
{
    while (true)
    {
        try
        {
            _socketConnection = new TcpClient(_server.ToString(), _server.Port);

            //...

为了在服务器发送一些数据并断开客户端连接后立即开始新的连接。

多亏 Damien_The_Unbeliever 和 Immersive 的帮助,我才弄明白了。不时阅读文档真的很有帮助,尤其是当您是第一次使用某些东西时 ^^

NetworkStream.Read 是一个 阻塞 调用,正如文档所述

returns: The number of bytes read from the NetworkStream, or 0 if the socket is closed.

当然 while 循环实际上从未终止。


所以采用那里提供的示例对我有用,除了如果服务器终止连接我遇到了另一个问题所以我没有检查 _socketConnection.IsConnected 我使用了 this post 的标记答案所以一起这现在对我有用

private Thread _tcpThread;
private TcpClient _socketConnection;

public void Connect()
{
    if(_socketConnection != null) return;

    try
    {
        _tcpThread = new Thread(ReciveDataClient);
        _tcpThread.IsBackground = true;
        _tcpThread.Start();
    }
    catch (Exception e)
    {
        print("TCP -> Thread error: " + e.Message);
    }
}

public void Disconnect()
{
    if(_socketConnection = null) return;

    _tcpThread.Abort();
}

private void ReciveDataClient()
{
    try
    {
        _socketConnection = new TcpClient("xxx.xxx.xxx.xxx", 54321);
        print(this, "TCP -> Connection Success!");
    }
    catch (Exception e)
    {
        print("TCP -> connection error: " + e.Message)
        return;
    }

    try
    {
        while(true)
        {
            // Get a stream object for reading              
            var netstream = _socketConnection.GetStream();

            //Check if still connected                
            if(_socketConnection.Client.Poll(0, SelectMode.SelectRead))
            {
                byte[] buff = new byte[1];
                if( _socketConnection.Client.Receive( buff, SocketFlags.Peek ) == 0 )
                {
                    // Server disconnected or connection lost
                    break;
                }
            }

            // Check to see if this NetworkStream is readable.
            if(myNetworkStream.CanRead)
            {
                byte[] myReadBuffer = new byte[BUFFER_SIZE];
                StringBuilder myCompleteMessage = new StringBuilder();
                int numberOfBytesRead = 0;
                int totalBytesReceived = 0;

                // Incoming message may be larger than the buffer size.
                do
                {
                    numberOfBytesRead = myNetworkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
                    myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));    
                    totalBytesReceived += numberOfBytesRead;        
                }
                while(myNetworkStream.DataAvailable);

                // Print out the received message to the console.
                print("TCP -> Data received:\n" + myCompleteMessage.ToString() + "\n\n" + totalrecbytes + " Bytes");
            }
            else
            {
                //Prevent a direct loop
                Thread.Sleep(100);
            }          
        }

        print("TCP -> connection was terminated by the server");
    }
    catch(ThreadAbortException)
    {
        print("TCP -> Disconnected");
    }
    catch(Exception e)
    {
        print(e.Message)
    }

    // Clean up
    _socketConnection?.Close();
    _socketConnection?.Dispose();
    _socketConnection = null;
}