示例#1
0
        public DataHeader(byte[] buffer, int RevNumber)
        {
            if (RevNumber < 31)
            {
                isValid = false;
                return;
            }

            //第一个字节
            isValid = (buffer[0] & 0x40) == 0x40;
            //第二个字节
            isValid = (buffer[1] & 0x40) == 0x40;

            //数据长度高低位
            byteLength[0] = buffer[3];
            byteLength[1] = buffer[2];

            dataLength = RevNumber;

            //数据包尾验证
            isValid = (buffer[dataLength - 1] & 0x0A) == 0x0A;
            isValid = (buffer[dataLength - 2] & 0x0D) == 0x0D;


            //设备ID
            _deviceId = new byte[20];
            Buffer.BlockCopy(buffer, 5, _deviceId, 0, 20);
            //数据类型
            _type = new byte[2];
            Buffer.BlockCopy(buffer, 25, _type, 0, 2);
            //数据内容
            _content = new byte[dataLength];
            Buffer.BlockCopy(buffer, 0, _content, 0, dataLength);

            deviceId = DataHander.HexStringToASCII(_deviceId).ToString().Trim('\0');

            type = DataHander.ByteToString(_type).Replace(" ", "");
        }
示例#2
0
        private void AcceptConn(IAsyncResult ar)
        {
            try
            {
                //如果服务器停止了服务,就不能再接收新的客户端
                if (!Started)
                {
                    return;
                }

                //缓冲区的大小
                byte[] buffer = new byte[512];

                //获取用户定义的对象,它限定或包含关于异步操作的信息。
                Socket listener = (Socket)ar.AsyncState;
                //异步接受传入的连接尝试,并创建新的 Socket 来处理远程主机通信。
                Socket client = listener.EndAccept(ar);

                Session state = new Session(m_id++, client);
                state.ChatEvent += new EventHandler <ChatEventArgs>(state_ChatEvent);

                //登录认证,只有等ReceiveLoginValidateCallback执行完后才会继续
                LoginValidataDone.Reset();
                client.BeginReceive(buffer, 0, 512, SocketFlags.None, new AsyncCallback(ReceiveLoginValidateCallback), client);
                LoginValidataDone.WaitOne();


                DataHeader dh = new DataHeader(buffer, num);

                IRec irec = new ReceiveData();
                irec.InsertRawData(DataHander.ByteToString(dh.Content).Replace(" ", ""), "");

                Handshake hh = new Handshake(Encoding.UTF8.GetString(buffer, 0, 512));

                //进行一个初步的协议判定,如果不是websocket协议,直接断开,忽略掉
                if (hh.GetValue("Upgrade").ToLower() != "websocket" && hh.GetValue("Upgrade").ToLower() != "")
                {
                    try
                    {
                        client.Shutdown(SocketShutdown.Both); client.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        using (StreamWriter sw = new StreamWriter(@"C:\Logs\job1" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true, System.Text.Encoding.UTF8))
                        {
                            sw.WriteLine(ex.Message);
                        }
                    }
                    //继续接受客户端
                    m_server.BeginAccept(new AsyncCallback(AcceptConn), m_server);
                    return;
                }
                if (dh.Type == "1001")
                {
                    state.Send(dh.GetLoginResponse());
                    try
                    {
                        var model = DataHander.LoginHander(dh);
                        irec.InsertGPSData(model);
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    //服务器作出握手回应
                    state.Response(hh.Response);
                }


                state.Start();

                //将客户端信息置于列表中
                if (hh.GetValue("Upgrade").ToLower() == "websocket")
                {
                    m_clients.Add(state.DevId, state);
                }


                //继续接受客户端
                m_server.BeginAccept(new AsyncCallback(AcceptConn), m_server);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //设置异步方法接受客户端连接
                m_server.BeginAccept(new AsyncCallback(AcceptConn), m_server);
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\job2" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true, System.Text.Encoding.UTF8))
                {
                    sw.WriteLine(ex.Message);
                }
            }
        }
示例#3
0
        /// <summary>
        /// 获取数据包长度
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static int Length(byte[] bytes)
        {
            string s = DataHander.ByteToString(bytes).Replace(" ", "");

            return(DataHander.GetHexadecimalValue(s));
        }
示例#4
0
        /// <summary>
        /// 应客户端要求建立连接后的处理线程
        /// </summary>
        /// <param name="ia"></param>
        private void AcceptCallBack(IAsyncResult ar)
        {
            try
            {
                //判断是否是websocket或socket
                //bool isWebsocket = true;
                //定义一个新的客户端对象
                Session state  = (Session)ar.AsyncState;
                Socket  client = state._workSocket;

                #region === 消息处理 ===

                //登录成功,则进入消息等待中
                int RevNumber = 0;

                if (client.Connected)
                {
                    #region === 正常或非正常的断线处理 ===

                    try
                    {
                        RevNumber = client.EndReceive(ar);
                        if (RevNumber == 0)
                        {
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        using (StreamWriter sw = new StreamWriter(@"C:\Logs\job13" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true, System.Text.Encoding.UTF8))
                        {
                            sw.WriteLine(ex.Message);
                        }
                        return;
                    }

                    #endregion
                    try
                    {
                        DataHeader dh = new DataHeader(RecvDataBuffer, RevNumber);
                        #region 原始数据插入数据库
                        IRec irec1 = new ReceiveData();
                        irec1.InsertRawData(DataHander.ByteToString(dh.Content).Replace(" ", ""), "");
                        #endregion


                        if (dh.IsValid)
                        {
                            IRec irec = new ReceiveData();
                            switch (dh.Type)
                            {
                            case "1001":
                                var model = DataHander.LoginHander(dh);
                                irec.InsertGPSData(model);
                                break;

                            case "4001":
                                var model1 = DataHander.GPSHander(dh);
                                irec.InsertGPSData(model1);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        using (StreamWriter sw = new StreamWriter(@"C:\Logs\job7" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true, System.Text.Encoding.UTF8))
                        {
                            sw.WriteLine(ex.Message);
                        }
                    }
                    //继续接收来自来客户端的数据
                    client.BeginReceive(RecvDataBuffer, 0, RecvDataBuffer.Length, SocketFlags.None,
                                        new AsyncCallback(AcceptCallBack), state);
                }
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                using (StreamWriter sw = new StreamWriter(@"C:\Logs\job6" + DateTime.Now.ToString("yyyyMMddHH") + ".txt", true, System.Text.Encoding.UTF8))
                {
                    sw.WriteLine(ex.Message);
                }
            }
        }