using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO; namespace GPS定位收发控制
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void Form1_Load(object sender, EventArgs e)
        {        }
        Thread mythread;
        Socket socket;        struct GpsInfo
        {
            public Double X, Y;
            public string DateStr, TimeStr;
        }
        struct UDPOutInfo
        {
            public string SBID, OutType, OutStr;
            public GpsInfo[] GpsInfos;
        }
        UDPOutInfo m_UDPOutInfo;        public static IPAddress GetServerIP()
        {
            IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
            return ieh.AddressList[0];
        }
        private void BeginListen()
        {
            IPAddress ServerIp = GetServerIP();
            String tmpPos = "", tmpMsgFrom = "";
            IPEndPoint iep = new IPEndPoint(ServerIp, int.Parse(tbLocalPort.Text));//定义一网络端点
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//定义一个Socket
            socket.Bind(iep);//Socket与本地的一个终结点相关联
            byte[] byteMessage = new byte[1024];
            int recv;
            while (true)
            {
                try
                {
                    //得到客户机IP
                    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//定义要发送终端地址
                    EndPoint Remote = (EndPoint)(sender);
                    recv = socket.ReceiveFrom(byteMessage, ref Remote);//接受数据//无信号时,一直陷于此处于监听状态
                    tmpPos = Remote.ToString();
                    string[] tmpIPDK=new string[2];
                    tmpIPDK = tmpPos.Split(':');
                    IPlabel.Text = tmpIPDK[0];
                    DKlabel.Text = tmpIPDK[1];
                    string sTime = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();                    tmpMsgFrom = dis_package(byteMessage, "X2", recv);                    //不安全线程调用,为防止报错,之前必须加行System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
                    rtbReceiveInfo.Items.Add(sTime + " 来自 " + tmpPos + " 的信息:" + "\r\n");
                    rtbReceiveInfo.Items.Add("收到字节内容:" + tmpMsgFrom + "\r\n");
                    string tmpRequest = tmpMsgFrom.Replace(" ", "");
                    GetGPSInfos(tmpRequest);
                    if (recv > 0)
                    {
                        //反馈应答信息
                        byteMessage = strToToHexByte(m_UDPOutInfo.OutStr);
                        socket.SendTo(byteMessage, byteMessage.Length, SocketFlags.None, Remote);
                        string sTime1 = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
                        richResponsion.Items.Add("应答时间:" + sTime1);
                        richResponsion.Items.Add("应答内容:" + m_UDPOutInfo.OutStr);
                    }
                    Array.Clear(byteMessage, 0, byteMessage.Length - 1);
                }
                catch (SocketException ex)
                {
                }
            }
        }        // 字节数组转16进制字符串
        public string dis_package(byte[] reb, string AType, int ANum)
        {
            string temp = ""; 
            //foreach (byte b in reb)
            //    temp += b.ToString("X2") + " ";
            for (int i = 0; i < ANum; i++)
                temp += reb[i].ToString(AType);
            if (temp != "")
                temp = temp.Substring(0, temp.Length - 1);
            return temp;
        }        private void GetGPSInfos(string AInStr)
        {
            int i = 0, tmpGPSNum = 0, tmpLengthX = 0, tmpLengthY = 0;
            string tmpType = "", tmpACK = "", tmpGPSInfos = "";
            ArrayList tmp_GPSInfoList = new ArrayList();
            //初始化
            m_UDPOutInfo.OutStr = "";
            m_UDPOutInfo.SBID = "";
            m_UDPOutInfo.OutType = "";
            Array.Resize(ref m_UDPOutInfo.GpsInfos, 0);
            //分析入口参数串
            tmpType = AInStr.Substring(7, 1);//截取终端发送的请求字符串,得到相应的命令。
            m_UDPOutInfo.OutType = tmpType;
            m_UDPOutInfo.SBID = AInStr.Substring(8, 10);//截取终端发送的请求字符串,得到终端ID。            if (tmpType == "1")   //是登录请求
            {
                //直接拼装返回串
                m_UDPOutInfo.OutStr = "FE000E01" + m_UDPOutInfo.SBID + "0100000FFE";
            }
            else if (tmpType == "2")         // 是数据响应请求
            {
                //GPS数据条数
                tmpGPSNum = Convert.ToInt32(ToD(AInStr.Substring(18, 2), 16));                //ACK数据包自增序号
                tmpACK = AInStr.Substring(20, 8);                //先拼装返回串,再将GPS数据插入数据
                m_UDPOutInfo.OutStr = "FE000F02" + m_UDPOutInfo.SBID + tmpACK + "00FE";                tmpGPSInfos = AInStr.Substring(28, AInStr.Length - 30);
                tmp_GPSInfoList = GetInfos(tmpGPSInfos, tmpGPSNum);                Array.Resize(ref m_UDPOutInfo.GpsInfos, tmpGPSNum);
                foreach (string tmpGPS in tmp_GPSInfoList)
                {
                    tmpLengthX = Convert.ToInt32(ToD(tmpGPS.Substring(12, 8), 16).Length) - 7;
                    tmpLengthY = Convert.ToInt32(ToD(tmpGPS.Substring(20, 8), 16).Length) - 7;                    m_UDPOutInfo.GpsInfos[i].X = Convert.ToDouble(ToD(tmpGPS.Substring(12, 8), 16).Insert(tmpLengthX, "."));
                    m_UDPOutInfo.GpsInfos[i].Y = Convert.ToDouble(ToD(tmpGPS.Substring(20, 8), 16).Insert(tmpLengthY, "."));
                    m_UDPOutInfo.GpsInfos[i].DateStr = ToD(tmpGPS.Substring(0, 2), 16) + "-" + ToD(tmpGPS.Substring(2, 2), 16) + "-" + ToD(tmpGPS.Substring(4, 2), 16);
                    m_UDPOutInfo.GpsInfos[i].TimeStr = ToD(tmpGPS.Substring(6, 2), 16) + ":" + ToD(tmpGPS.Substring(8, 2), 16) + ":" + ToD(tmpGPS.Substring(10, 2), 16);
                    i++;
                }
            }
            else if (tmpType == "3") //是心跳请求
            {
                //直接拼装返回串
                m_UDPOutInfo.OutStr = "FE000B03" + m_UDPOutInfo.SBID + "00FE";
            }        }        //字符串转十六进制数组
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }        //实现十六进制转化为十进制
        public static string ToD(string Num, int n)
        {
            char[] nums = Num.ToCharArray();
            int d = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                string number = nums[i].ToString();
                if (n == 16)
                {
                    switch (number.ToUpper())
                    {
                        case "A":
                            number = "10";
                            break;
                        case "B":
                            number = "11";
                            break;
                        case "C":
                            number = "12";
                            break;
                        case "D":
                            number = "13";
                            break;
                        case "E":
                            number = "14";
                            break;
                        case "F":
                            number = "15";
                            break;
                    }
                }
                Double power = Math.Pow(Convert.ToDouble(n), Convert.ToDouble(nums.Length - (i + 1)));
                d = d + Convert.ToInt32(number) * Convert.ToInt32(power);
            }
            return d.ToString();
        }        //平均截取GPS数据信息
        public static ArrayList GetInfos(string Astr, int num)
        {
            ArrayList tmpGPSInfos = new ArrayList();
            int a = Astr.Length;
            int b = 40;
            for (int i = 0; i < num; i++)
            {
                int start = (b * i);
                tmpGPSInfos.Add(Astr.Substring(start, 40));
            }
            return tmpGPSInfos;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Application.ExitThread();
            if (socket != null)
                socket.Close();//释放资源 
            if (mythread != null)
                mythread.Abort();//中止线程 
            mythread = null;
            socket = null;
            btnStart.Enabled = true;
            rtbReceiveInfo.Clear();
        }        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            try
            {
                mythread = new Thread(new ThreadStart(BeginListen));
                mythread.Start();
            }            catch (System.Exception er)
            {
                MessageBox.Show(er.Message, "完成", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }    }
}用的UDP协议,能跟终端通信上,能响应终端的登录请求,并成功应答,但是却得不到终端发送回来的GPS数据包,这是什么原因啊?