如何使用用户数据报协议(UDP)

时间:2018-01-29 12:24:43

标签: c#

我有一台设备需要通过主机与C#进行通信,并通过以太网线连接设备和主机之间的交换帧。设备有一个端口和ip可以连接。以下是发送方和接收方之间的帧通信的示例代码。 我对C#知之甚少,我想在如何使用UDP协议套件建立通信方面提供一些帮助。谢谢

//Grab the data of the device
    private byte[] Fetch_FrameID(bool bHostToDevice)    //true:Host to Device false: Device to Host
    {
        return bHostToDevice ? new byte[] { 0x8F, 0xE1 } : new byte[] { 0x2D, 0x7A };
    }

    //Grab the Frame Sequence Number
    private byte[] Fetch_FrameSequenceNumber(int iNumber)
    {
        return new byte[] { (byte)(iNumber & 0xFF), (byte)((iNumber >> 8) & 0xFF) };
    }

    //Grab the device status
    private byte[] Fetch_HostToDeviceCommand(int iStatus)   //status:0:Active 1:Sync 2:Request
    {
        switch (iStatus)
        {
            case 0: return new byte[] { 0x00, 0x00 };     //Active
            case 1: return new byte[] { 0x11, 0x00 };     //Sync
            case 2: return new byte[] { 0x21, 0x00 };     //Request 
            default: return null;
        }
    }

    //Fetch Data Length
    private byte[] Fetch_DataLen(byte[] dataArray)
    {
        int iLength = dataArray == null ? 0 : dataArray.Length;
        return new byte[] { (byte)(iLength & 0xFF), (byte)((iLength >> 8) & 0xFF) };
    }

    //Fetch Data Check  Sum
    private byte[] Fetch_DataCheckSum(byte[] dataArray)
    {
        int iSum = 0;
        if (dataArray != null)
        {
            for (int i = 0; i < dataArray.Length; i++)
            {
                iSum += (int)dataArray[i];
            }
        }
        iSum += Convert.ToInt32("0xAA55", 16);
        return new byte[] { (byte)(iSum & 0xFF), (byte)((iSum >> 8) & 0xFF) };
    }


    private byte[] Fetc_SendHeaderInfo(int iStatus, int iNumber, byte[] dataArray)  //status:0:Active 1:Sync 2:Request
    {
        List<byte> result = new List<byte>();//TOTAL 12Bytes, each 2bytes
        result.AddRange(Fetch_FrameID(true));//Grab FrameID
        result.AddRange(Fetch_FrameSequenceNumber(iNumber));//Grab the FSN
        result.AddRange(Fetch_HostToDeviceCommand(iStatus));//Grab host to device command
        result.AddRange(Fetch_DataLen(dataArray));//Grab the data Length
        result.AddRange(Fetch_DataCheckSum(dataArray)); //Grab the data Check sum
        result.AddRange(Fetch_DataCheckSum(result.ToArray())); //Grab the headdata Check sum
        return result.ToArray();
    }

1 个答案:

答案 0 :(得分:1)

UDP和TCP是不同的协议,为了使用.NET C#发送UDP数据包我建议使用UdpClient,这里有一个示例代码,如果有帮助的话发送:

UdpClient udpClient = new UdpClient(ip, port);

try{
    udpClient.Send(bytesToSend, bytesToSendLength);
}
catch ( Exception e ){
    Console.WriteLine( e.ToString());
}

至于接收,您可以使用UdpClient.Receive

以下是Send&amp; MSDN上的Receive文档