C#TCP客户端读取偶尔不会收到任何数据 - “没有”

时间:2016-01-26 11:00:44

标签: c# string tcp tcpclient tcp-ip

我编写了一个与服务器通信的TCP客户端。在专用的“监听”主题中,我有如下代码。它应该只在有数据时读取数据。 (if (stream.DataAvailable)

奇怪的是,偶尔我的程序会崩溃,因为流将完全读取数据。它将返回一个空的string。更奇怪的是,如果我尝试在handleResponse(string s)函数中“捕获”一个空字符串,它就不会被捕获。

    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.NullReferenceException函数的行if ((desrlzdResp.instruction != null))上引发的异常handleResponse

1 个答案:

答案 0 :(得分:3)

网络流习惯于在数据不活动时宣传数据。此外,接收方无法知道传入流的长度,除非发送方事先通知它。

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

注意 - 可能不需要在发送方进行刷新,但我添加了它,因为它没有任何损害 - 微软称flush对网络流没有任何作用。

因此,此代码将确定您要发送的邮件的大小,然后在您的“实际”邮件之前将其发送给接收方。消息。

        /// <summary>
        /// Incoming bytes are retieved 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周期。