在UdpClient接收器上丢失了包

时间:2015-06-24 19:34:50

标签: c# network-programming

我的应用程序使用UdpClient从其他机器接收图像 每个图像大小为951000字节,MTU限制为1500字节。

因此发件人应用程序必须使用碎片...并且每个发送包都包含包含2 int

的标头
  1. TOTAL_NUMBER
  2. current_number
  3. 代码接收字节.. ..这是非常密集的比特率,因为视频每30毫秒有一个新帧发送到我的应用程序..

    我发现自己失去了包裹,我不知道如何做到与众不同,而不是丢失包裹。

    有人知道如何解决这个问题吗? 有没有更好的方法?

    这是代码

    public class PackagePartial
    {
        public int total_count;
        public int current_count; // first package is 1  
        public byte[] buffer;
    
        public byte[] Serializable()
        {
            // make the Serialize
        }
    
        public static void DeSerializable(byte[] v)
        {
            total_count = ... ;
            current_count = ... 
            buffer = ... 
        }
    }
    
    // the network layer 
    int lastPackIndex = 0;
    List<byte> collection = new List<byte>();
    while(true)
    {
          byte[] package = _clientListener.Receive(ref ep);
    
           PackagePartial p = PackagePartial.DeSerializable(package);
    
           // indication that i lost package
           if(p.current_count - lastPackIndex != 1 )
           {
             collection.Clear();
             lastPackIndex = 0
             continue;               
    
           }
    
           if(p.current_count == p.total_count)
           {
                 // image Serialize and send it to the GUI layer as bitmap 
                 Image img = ConvertBytesToImage(collection);
    
                 SendToGui(img);
    
                 collection.Clear();
    
                 lastPackIndex = 0
    
           }
           else
           {
                 lastPackIndex = p.current_count
                 collection.AddRange(p.Buffer)
           }
    

1 个答案:

答案 0 :(得分:0)

收到后,不要将每个包反序列化为中间类。

创建一个字节数组列表,并在它们进入时将它们全部填入其中。

一旦另一方完成发送,请查看第一个查找总计数并查看List.Count是否与总计数匹配。

如果确实如此,你拥有所有的包,现在你可以重新组装图像,只需忽略标题,你就不再需要了它们。

由于此时你不需要任何东西,但每个数据包的数据,组装图像应该更快(不再涉及到中间类的序列化)。

这应该最小化每个图像所需的处理。