c#TCP数据包丢失

时间:2018-01-12 15:15:40

标签: c# tcp

我正在尝试在服务器和客户端之间通过网络发送一些字符串。它适用于小字符串(高达~14​​00字节),但是一旦我发送超过1400字节的数据,大多数时候我只得到1400字节,数据> 1400字节丢失。 Hier是我的客户代码:

    public static string Senddata(string BarcodeText)
    {
        try
        {
            string textToSend = BarcodeText.ToString();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
            //---send the text---
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);
            return "Success";//if sent
        }
        catch (Exception)
        {
            return "Fail";//if not sent
        }
    }

    // Recieve Data from Server
    public static string Getdata()
    {
        try
        {
            int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
            str = Encoding.GetEncoding("ISO-8859-1").GetString(bytesToRead, 0, bytesRead);
            return str;
        }
        catch (Exception)
        {
            return "Did not recieved anything from Virtual PC";
        }
    }

Hier是服务器的代码:

    public static string GetDatafromClient()
    {
        try
        {
            //---get the incoming data through a network stream---
            nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];
            //Console.WriteLine("buffer");
            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            return Encoding.ASCII.GetString(buffer, 0, bytesRead);
        }
        catch (Exception)
        {
            return "-";
        }

    }

    public static void SendDatatoClient(string DataToSend)
    {
        FileHandling.SaveToFile(DataToSend);
        //---write back the text to the client---
        byte[] bytesTosend = Encoding.GetEncoding("ISO-8859-1").GetBytes(DataToSend);
        nwStream.Write(bytesTosend, 0, bytesTosend.Length);
    }

2 个答案:

答案 0 :(得分:1)

你可以像MSDN example

那样进行循环
// Examples for CanRead, Read, and DataAvailable.

// Check to see if this NetworkStream is readable.
if(myNetworkStream.CanRead){
    byte[] myReadBuffer = new byte[1024];
    StringBuilder myCompleteMessage = new StringBuilder();
    int numberOfBytesRead = 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));
    }
    while(myNetworkStream.DataAvailable);

    // Print out the received message to the console.
    Console.WriteLine("You received the following message : " + myCompleteMessage);

    else{
    Console.WriteLine("Sorry.  You cannot read from this NetworkStream.");
}

问题可能是您的数据是在多个“包”中发送的。有很多方法可以解决这个问题。 Length byte就是其中之一。另一种解决方案是使用成帧字节。 - >你把数据放在这个字节之间,这样就知道了开始和结束 - > 0x02数据0x03。

从长远来看,使用REST等高级协议可能更简单。

答案 1 :(得分:1)

所以,我通过发送前4个字节作为数据长度然后实际数据来解决这个问题,现在我得到0个数据丢失。谢谢所有人帮我。客户端看起来像:

        public static string Getdata()
    {
        try
        {
            byte[] DataLengthinBytes = new byte[4];
            nwStream.Read(DataLengthinBytes, 0, 4);
            int DataLength = BitConverter.ToInt32(DataLengthinBytes, 0);
            byte[] bytesToRead = new byte[DataLength];
            StringBuilder str = new StringBuilder();
            int bytesRead = 0;
            int i = 0;
            while(i < DataLength){
                bytesRead = nwStream.Read(bytesToRead, 0, DataLength);
                str.AppendFormat("{0}", Encoding.GetEncoding("ISO-8859-1").GetString(bytesToRead, 0, bytesRead));
                i += bytesRead;
            }
            return str.ToString();
        }
        catch (Exception)
        {
            return "Did not recieved anything from Virtual PC";
        }
    }

和服务器端:

        public static void SendDatatoClient(string DataToSend)
    {
        //---write back the text to the client---
        byte[] bytesTosend = Encoding.GetEncoding("ISO-8859-1").GetBytes(DataToSend);
        byte[] Datalength = BitConverter.GetBytes((Int32)bytesTosend.Length);
        nwStream.Write(Datalength, 0, 4);
        nwStream.Write(bytesTosend, 0, bytesTosend.Length);
    }