简体   繁体   中英

What happens if udpclient lost packets in C#

I'm studying computer network nowadays. Now I know a big difference between TCP and UDP is that UDP can lose their packets while communication. I'm wondering how C# react with this lost. For example, one host sends "ABCD\\n" string to another host. If there were the lost of packet, does the receiving host throw any exception or just got like "AB\\n" ? (addition) and i want to know some way to enforce for udpclient to lose their packet. then i can do experiment.

C# couldn't care less - in fact it won't even know a packet was lost. Your code/logic may or may not have issues with that lost packet. That's entirely up to the logic you coded, and has nothing to do with the underlying programming language/runtime system.

I also think you're overthinking/overcomplicating this: losing a packet === not sending one...

You should implement a CRC mechanism by yourself (language agnostic)

For example:

host1 wants to send to host2 an udp datagram.

  1. host1 computes packet crc and then send the packet to host2.
  2. when host2 receives the packet should compute the packet crc and then replies to host1 with that value.
  3. host1 compares both crc values and if match the packet was sent correct and arrived to host2 . If not host1 must resend packet.

Here's a C# crc class example:

public static class Crc16
{
    const ushort polynomial = 0xA001;
    static readonly ushort[] table = new ushort[256];

    public static ushort ComputeChecksum(byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }

    static Crc16()
    {
        ushort value;
        ushort temp;
        for (ushort i = 0; i < table.Length; ++i)
        {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j)
            {
                if (((value ^ temp) & 0x0001) != 0)
                {
                    value = (ushort)((value >> 1) ^ polynomial);
                }
                else
                {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM