C# TCP 客户端读取偶尔接收不到数据 - 'nothing'

C# TCP client read occasionally receives no data - 'nothing'

我编写了一个与服务器通信的 TCP 客户端。在专用的 'listening' 线程中,我有如下代码。它应该只在有数据时才读取数据。 (if (stream.DataAvailable))

奇怪的是,有时我的程序会崩溃,因为流绝对不会读取任何数据。它将 return 一个空的 string。更奇怪的是,如果我尝试在 handleResponse(string s) 函数中 'catch' 一个空字符串,它不会被捕获。

    public void listenForResponses()
    {
        Console.WriteLine ("Listening...");
        while (isConnected == true)
        {
            Thread.Sleep (updateRate);
            String responseData = String.Empty;

            if (stream.DataAvailable) {
                Int32 bytes = stream.Read (data, 0, data.Length);
                Console.WriteLine (" >> Data size = "+data.Length);
                responseData = System.Text.Encoding.ASCII.GetString (data, 0, bytes);
                output = responseData+"";
                handleResponse (output);
            }
            if (isConnected == false) {
                closeConnection ();
            }
        }
    }

public void handleResponse(string msg)
{
    Console.WriteLine ("Received: "+msg); 
    iterateThroughEachCharInString (msg);
    if ((msg != "")&&(msg != null)&&(msg != " ")) {
        JSONDataObject desrlzdResp = JsonConvert.DeserializeObject<JSONDataObject>(msg);

        if ((desrlzdResp.instruction != null)) {
            if (desrlzdResp.instruction == "TestConn") {
                handleTestConn (desrlzdResp);
            } else if (desrlzdResp.instruction == "SceneOver") {
                handleSceneFinished (desrlzdResp);
            }
        }
    }
}

抛出的异常是System.NullReferenceExceptionhandleResponse函数的if ((desrlzdResp.instruction != null))

Network Streams 有一种习惯,即使在它们不活动时也会宣传可用的数据。此外,接收方无法知道传入流的长度,除非发送方事先通知它。

        /// <summary>
        /// Method designed to allow the sending of Byte[] data to the Peer
        /// Because this is using NetworkStreams - the first 4 bytes sent is the data length
        /// </summary>
        /// <param name="TheMessage"></param>
        public void SendBytesToPeer(byte[] TheMessage)
        {

            try
            {
                long len = TheMessage.Length;

                byte[] Bytelen = BitConverter.GetBytes(len);

                PeerStream.Write(Bytelen, 0, Bytelen.Length);
                PeerStream.Flush();
                PeerStream.Write(TheMessage, 0, TheMessage.Length);
                PeerStream.Flush();
            }
            catch (Exception e)
            {
                //System.Windows.Forms.MessageBox.Show(e.ToString());
            }
        }

注意 - 发送端的刷新可能不需要,但我添加它是因为它没有害处 - Microsoft 说刷新对网络流没有任何作用。

因此此代码将确定您要发送的消息的大小,然后在 'actual' 消息之前将其发送给接收者。

        /// <summary>
        /// Incoming bytes are retrieved in this method
        /// </summary>
        /// <param name="disconnected"></param>
        /// <returns></returns>
        private byte[] ReceivedBytes(ref bool disconnected)
        {
            try
            {
                //byte[] myReadBuffer = new byte[1024];
                int receivedDataLength = 0;
                byte[] data = { };
                int len = 0;
                int i = 0;
                PeerStream.ReadTimeout = 15000;


                if (PeerStream.CanRead)
                {
                    //networkStream.Read(byteLen, 0, 8)
                    byte[] byteLen = new byte[8];
                    if (_client.Client.IsConnected() == false)
                    {
                        //Fire Disconnect event
                        if (OnDisconnect != null)
                        {
                            disconnected = true;
                            OnDisconnect(this);
                            return null;
                        }
                    }
                    while (len == 0)
                    {
                        PeerStream.Read(byteLen, 0, 8);

                        len = BitConverter.ToInt32(byteLen, 0);
                    }
                    data = new byte[len];

                    PeerStream.Read(data, receivedDataLength, len);

                    return data;
                }



            }
            catch (Exception E)
            {

                //System.Windows.Forms.MessageBox.Show("Exception:" + E.ToString());
            }
            return null;
        }

此代码将等到接收器检测到传入流的长度,然后尝试读取该确切长度。 不要担心 OnDisconnect 位 - 这只是我从我正在做的项目中留下的一些代码。您可能需要考虑在 while(len == 0) 循环中添加一个 Thread.Sleep,以节省您的 CPU 周期。