TCP数据包丢失

时间:2018-08-28 11:56:55

标签: c# sockets tcp

我将视频流从一个c#应用程序传输到另一个。当我将帧率设置得很高时,过了一段时间我没有得到正确的数据。

//Receiver
Socket s;
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
var ip = IPAddress.Any;
myList = new TcpListener(ipAd, 8001);
myList.Start();
s = myList.AcceptSocket();

while (runThread)
{
        int buffertype = -1; MemoryStream img = null; int size = 0; int 
        pos = 0;
        try
        {
            // length of frame
            byte[] lengthb = new byte[32];
            int k = s.Receive(lengthb, SocketFlags.None);
            size = BitConverter.ToInt32(lengthb, 0);
            pos = 0;

            byte[] lengthframe = new byte[size];
            // chunking of data
            int chunksize = 100;
            while (pos < size - chunksize)
            {
                int rec = s.Receive(lengthframe, pos, chunksize, SocketFlags.None);
                pos += rec;
            }
            s.Receive(lengthframe, pos, size - pos, SocketFlags.None);

            img = new MemoryStream(lengthframe);
        }
 }

 // Other app: Sender (all is send)
 MemoryStream ms = new MemoryStream();
 img.CopyTo(ms);                
 byte[] ba = ms.ToArray();
 var buffer = BitConverter.GetBytes(ba.Length);
 stm.Write(buffer, 0, buffer.Length);
 stm.Write(ba, 0, ba.Length);

如何安全地收到所有包裹?

1 个答案:

答案 0 :(得分:1)

发件人:

stm.Write(buffer, 0, buffer.Length);

接收器:

byte[] lengthb = new byte[32];
int k = s.Receive(lengthb, SocketFlags.None);

您确定buffer.Length类型是32字节长(256位)吗?我想它的长度是4或8个字节。因此,您可能会收到32个字节的缓冲区,该缓冲区在开始时包含length字段,其余的则是编码视频流的一部分。然后,您丢弃那部分。听起来不好。