如何从UDP数据包c#接收获取实际数据

时间:2015-09-01 14:51:35

标签: c# sockets networking udp

我有一个小程序来接收UPD数据包。我收到数据包有点问题。我实际上需要通过id转发数据包,例如" position(数据包ID:196),位置:187等"使用我的代码我得到一些数据,但我不知道如何找到id以及如何在数据包中获取真实数据。

数据包标头

| SYNC字节| SYNC字节|数据长度|标识符|数据字节|校验|

| 1(0x24)| 2(0x40)|字节|再见| | Byete |

字段:同步字节大小:2个字节

字段:数据长度大小:1个字节

字段:数据包标识符大小:1个字节

字段:数据大小:0-255字节
字段:校验和大小:1个字节

enter code here
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;


namespace SimpleUdpReciever
{
    class pProgram
    {
        static void Main(string[] args)
        {
            int localPort = 18006;
            IPEndPoint remoteSender = new IPEndPoint(IPAddress.Any, 0);
            bool flag = false;

            for (int i = 0; i < args.Length; i++)
            {
                string cmd = args[i];
                string value;
                int tempInt;
                IPAddress tempAddress;

                switch (cmd)
                {
                    case "-lp":
                        value = GetValue(args, ref i);
                        if (int.TryParse(value, out tempInt))
                            localPort = tempInt;
                        break;
                    case "-rp":
                        value = GetValue(args, ref i);
                        if (int.TryParse(value, out tempInt))
                            remoteSender.Port = tempInt;
                        break;
                    case "-rh":
                        value = GetValue(args, ref i);
                        if (IPAddress.TryParse(value, out tempAddress))
                            remoteSender.Address = tempAddress;
                        else if (int.TryParse(value, out tempInt) && tempInt == 0)
                            remoteSender.Address = IPAddress.Any;
                        break;
                    case "-?":
                    default:
                        PrintHelpText();
                        flag = true;
                        break;
                }
            }

            // Exit application after help text is displayed
            if (flag)
                return;



            // Create UDP client
            UdpClient client = new UdpClient(localPort);
            UdpState state = new UdpState(client, remoteSender);
            // Start async receiving
            client.BeginReceive(new AsyncCallback(DataReceived), state);

            // Wait for any key to terminate application
            Console.ReadKey();
            client.Close();
        }


        private static void DataReceived(IAsyncResult ar)
        {
            UdpClient c = (UdpClient)((UdpState)ar.AsyncState).c;
            IPEndPoint wantedIpEndPoint = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
            IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            Byte[] receiveBytes = c.EndReceive(ar, ref receivedIpEndPoint);

            bool isRightHost = (wantedIpEndPoint.Address.Equals(receivedIpEndPoint.Address)) || wantedIpEndPoint.Address.Equals(IPAddress.Any);
            bool isRightPort = (wantedIpEndPoint.Port == receivedIpEndPoint.Port) || wantedIpEndPoint.Port == 0;
            if (isRightHost && isRightPort)
            {        string test5 = Encoding.ASCII.GetString(receiveBytes);

                Console.WriteLine("test5 = {0}", test5);




            }

            // Restart listening for udp data packages
            c.BeginReceive(new AsyncCallback(DataReceived), ar.AsyncState);

        }


        private static string GetValue(string[] args, ref int i)
        {
            string value = String.Empty;
            if (args.Length >= i + 2)
            {
                i++;
                value = args[i];
            }
            return value;
        }



        private static void PrintHelpText()
        {
            Console.WriteLine("Simple Udp Receiver is an application that prints incoming data to screen.");
            Console.WriteLine("Data is converted to ASCII before printing.");[![enter image description here][1]][1]           
            Console.WriteLine("Command switches:");
            Console.WriteLine("-? : Displays this text.");
            Console.WriteLine("-lp : Set local receiving port. \"-lp 4001\" Default: 11000");
            Console.WriteLine("-rp : Set remote sender port. \"-rp 4001\" Default: 0 (Any port)");
            Console.WriteLine("-rh : Set remote sender ip. \"-rh 192.168.1.10\" Default: 0 (Any ip)");
            Console.WriteLine("\n Example of usage:\nSimpleUdpReciver.exe -lp 11000 -rh 192.168.10.10 -rp 4001");
        }

    }
}

Out put看起来像这样运行这个程序:$ @za��X ���

0 个答案:

没有答案