Ejemplo n.º 1
0
 /// <summary>
 /// Session结束事件调用
 /// </summary>
 /// <param name="_session">SocketSession 对象</param>
 internal virtual void OnSessionEnd(SocketSession _session)
 {
     if (this.OnSessionEndEvent != null && _session != null)
     {
         this.OnSessionEndEvent(_session);
     }
 }
Ejemplo n.º 2
0
        public byte[] EnPackage(object _object, SocketSession _session = null)
        {
            string _json = ((JObject)_object).ToString(Newtonsoft.Json.Formatting.None);
            string _data = OpenSSLAes.Encode(_json, this.key) + "\n";

            return(Encoding.UTF8.GetBytes(_data));
        }
Ejemplo n.º 3
0
        public byte[] EnPackage(object _object, SocketSession _session = null)
        {
            WstpPackage _package = (WstpPackage)_object;

            int _payloadByte = 0;

            if (_package.Binary.Length >= 65536)
            {
                _payloadByte = 8;
            }
            else if (_package.Binary.Length >= 126)
            {
                _payloadByte = 2;
            }

            byte[] _data = new byte[2 + _payloadByte + _package.Binary.Length];
            _data[0]  = 0;
            _data[1]  = 0;
            _data[0] |= 0x80;
            switch (_package.Type)
            {
            case WstpPackageType.Ping: _data[0] |= 0x09; break;

            case WstpPackageType.Pong: _data[0] |= 0x0A; break;

            case WstpPackageType.Text: _data[0] |= 0x01; break;

            case WstpPackageType.Binary: _data[0] |= 0x02; break;

            case WstpPackageType.Close: _data[0] |= 0x08; break;
            }
            if (_payloadByte == 0)
            {
                _data[1] = (byte)_package.Binary.Length;
                Array.Copy(_package.Binary, 0, _data, 2, _package.Binary.Length);
            }
            else if (_payloadByte == 2)
            {
                _data[1] = 126;

                ushort _size    = ushort.Parse(_package.Binary.Length.ToString());
                short  _sizeNet = System.Net.IPAddress.HostToNetworkOrder((short)_size);
                byte[] _length  = BitConverter.GetBytes(_sizeNet);
                Array.Copy(_length, 0, _data, 2, _length.Length);
                Array.Copy(_package.Binary, 0, _data, 4, _package.Binary.Length);
            }
            else
            {
                _data[1] = 127;

                int    _size    = _package.Binary.Length;
                long   _sizeNet = System.Net.IPAddress.HostToNetworkOrder((long)_size);
                byte[] _length  = BitConverter.GetBytes(_sizeNet);
                Array.Copy(_length, 0, _data, 2, _length.Length);
                Array.Copy(_package.Binary, 0, _data, 10, _package.Binary.Length);
            }

            return(_data);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 开始接受连入
        /// </summary>
        private void BeginAccept()
        {
            while (!this._shutingdown)
            {
                SocketSession _socketSession = this.Sessions.Pop();
                if (_socketSession == null)
                {
                    Thread.Sleep(100); continue;
                }

                #region Session池可用
                _socketSession.Handshaked = false;
                _socketSession.Status     = SocketSessionStatus.Accepting;

                try
                {
                    try
                    {
                        if (!this.socket.AcceptAsync(_socketSession.SocketAsyncEventArgs))
                        {
                            this.EndAccept(_socketSession.SocketAsyncEventArgs);
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        int _index = _socketSession.Index;
                        _socketSession.Dispose();

                        _socketSession = new SocketSession(this, _index);
                        _socketSession.SocketAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(Async_Completed);
                        this.Sessions[_index] = _socketSession;

                        if (!this.socket.AcceptAsync(_socketSession.SocketAsyncEventArgs))
                        {
                            this.EndAccept(_socketSession.SocketAsyncEventArgs);
                        }
                    }
                }
                catch (ObjectDisposedException _ex)
                {
                    if (_ex.ObjectName != "Socket")
                    {
                        this.OnException(_ex);
                    }
                }
                catch (Exception _ex)
                {
                    this.OnException(_ex);
                }
                #endregion

                return;
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Session开始事件调用
 /// </summary>
 /// <param name="_session">SocketSession 对象</param>
 internal virtual void OnSessionStart(SocketSession _session)
 {
     if (this._shutingdown)
     {
         return;
     }
     if (this.OnSessionStartEvent != null && _session != null)
     {
         this.OnSessionStartEvent(_session);
     }
 }
Ejemplo n.º 6
0
        public bool ReceiveFirstPackage(JObject _json, SocketSession _session)
        {
            if (_session["TxKey"] + "" != "" && _session["Checksum"] + "" == "DONE")
            {
                return(false);
            }

            if (_session["RxKey"] + "" == "")
            {
                DateTime _time = DateTimePlus.JSTime2DateTime(long.Parse(_json["time"].Value <string>()));
                if (Math.Abs((_time - DateTime.UtcNow).TotalSeconds) > 300)
                {
                    _session.Disconnect(); return(true);
                }

                _session["TxKey"] = _json["key"].Value <string>();

                Random _random = new Random(RandomPlus.RandomSeed);
                string _rxKey  = _random.Next(10000000, 100000000).ToString();
                _session["RxKey"] = _rxKey;
                string _checksum = _random.Next(10000000, 100000000).ToString();
                _session["Checksum"] = _checksum;

                JObject _result = new JObject();
                _result["check"] = this.rsa.Sign(_json["num"].Value <string>());
                _result["num"]   = _checksum;
                _result["key"]   = _rxKey;

                _session.SendPackage(_result);
            }
            else if (_session["Checksum"] + "" != "DONE")
            {
                if (!this.rsa.Verify(_session["Checksum"] + "", _json["check"].Value <string>()))
                {
                    this.socketTxKey = "";
                    return(true);
                }

                _session["Checksum"] = "DONE";
                _session.Handshaked  = true;
            }
            return(true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 接受到连入处理
        /// </summary>
        /// <param name="_socketAsyncEventArgs">异步Socket对象</param>
        private void EndAccept(SocketAsyncEventArgs _socketAsyncEventArgs)
        {
            SocketSession _socketSession = (SocketSession)_socketAsyncEventArgs.UserToken;

            if (_socketAsyncEventArgs.SocketError != SocketError.Success || !this.OnSocketAccept(_socketAsyncEventArgs.AcceptSocket))
            {
                _socketSession.Clear();
                this.BeginAccept();
                return;
            }
            if (!this.bufferManager.SetBuffer(_socketAsyncEventArgs))
            {
                throw new OverflowException("Out of buffer.");
            }

            try
            {
                if (this.keepAliveIO)
                {
                    _socketAsyncEventArgs.AcceptSocket.IOControl(IOControlCode.KeepAliveValues, this.keepAliveByteArray, null);
                }

                DateTime _now = DateTime.UtcNow;
                _socketSession.LastOperationTime = _now;
                _socketSession.Id     = _now.ToString("yyyyMMddHHmmss") + _socketSession.Index.ToString("00000000");
                _socketSession.Status = SocketSessionStatus.Connected;

                this.OnSessionStart(_socketSession);
                this.BeginReceive(_socketAsyncEventArgs);
            }
            catch (Exception)
            {
                this.bufferManager.FreeBuffer(_socketAsyncEventArgs);
                _socketSession.Clear();
            }
            finally
            {
                this.BeginAccept();
            }
        }
Ejemplo n.º 8
0
        private void Timeout()
        {
            while (this.timeroutThreadRunning)
            {
                for (int i = 0; i < this.Sessions.Length; i++)
                {
                    SocketSession _socketSession = this.Sessions[i];
                    if (_socketSession.Status != SocketSessionStatus.Connected)
                    {
                        continue;
                    }

                    uint _keep = _socketSession.Protocol == null ? this.keepAlive : _socketSession.Protocol.KeepAlive;
                    if (_keep > 0 && _socketSession.LastOperationTime.AddMilliseconds(_keep) < DateTime.UtcNow)
                    {
                        _socketSession.Handshaked = false;
                        _socketSession.Disconnect();
                    }
                }
                Thread.Sleep(1000);
            }
        }
Ejemplo n.º 9
0
        public byte[] EnPackage(object _object, SocketSession _session = null)
        {
            string _key = "";

            if (_session == null)
            {
                _key = this.socketTxKey == "" ? this.socketKey : this.socketTxKey;
            }
            else
            {
                _key = _session["TxKey"] + "";
            }
            if (_key == "")
            {
                throw new Exception("EnPackage failed: TxKey is empty.");
            }

            string _content = ((JObject)_object).ToString(Newtonsoft.Json.Formatting.None);

            byte[] _contentArray = DES.Encode2ByteArray(System.Text.Encoding.UTF8.GetBytes(_content), _key, System.Security.Cryptography.CipherMode.CBC);
            uint   _length       = uint.Parse(_contentArray.Length.ToString()) + 4 + 16;

            byte[] _lengthArray = BitConverter.GetBytes(_length);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(_lengthArray);
            }

            byte[] _byteArray = new byte[_length - 16];
            Array.Copy(_lengthArray, _byteArray, 4);
            Array.Copy(_contentArray, 0, _byteArray, 4, _contentArray.Length);

            byte[] _md5Array = MD5.Encode2ByteArray(_byteArray);
            Array.Resize(ref _byteArray, _byteArray.Length + 16);
            Array.Copy(_md5Array, 0, _byteArray, _byteArray.Length - 16, 16);

            return(_byteArray);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 开始监听端口
        /// </summary>
        /// <param name="_endPoint">监听端口</param>
        /// <returns>是否成功监听端口</returns>
        private bool Listen(EndPoint _endPoint)
        {
            try
            {
                this.type = SocketEngineType.Server;

                this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                this.socket.LingerState.LingerTime = 0;

                this.socket.Bind(_endPoint);
                this.socket.Listen(this.limitedPending);

                this.bufferManager = new SocketEngineBuffer(this.LimitedSession, 4096);
                this.bufferManager.Init();

                this.Sessions = new SocketSessionCollection(this.limitedSession);
                for (int i = 0; i < this.LimitedSession; i++)
                {
                    SocketSession _socketSession = new SocketSession(this, i);
                    _socketSession.SocketAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(Async_Completed);
                    this.Sessions[i] = _socketSession;
                }

                this.timeroutThreadRunning = true;
                this.timeoutThread         = new Thread(new ThreadStart(this.Timeout));
                this.timeoutThread.Start();

                this.BeginAccept();

                return(true);
            }
            catch (Exception _ex)
            {
                this.OnException(_ex);
                return(false);
            }
        }
Ejemplo n.º 11
0
        public bool Check(byte[] _byteArray, bool _completely = false, SocketSession _session = null)
        {
            object _data = this.DePackage(_byteArray, out uint _packageSize, false, _session);

            return(_data != null);
        }
Ejemplo n.º 12
0
        public object DePackage(byte[] _byteArray, out uint _packageSize, bool _completely = false, SocketSession _session = null)
        {
            if (_session == null)
            {
                _packageSize = uint.Parse(_byteArray.Length.ToString()); return(null);
            }

            string _data = "";

            if (_session["__I__N__I__T__"] == null)
            {
                #region 首次握手
                _data = Encoding.UTF8.GetString(_byteArray);
                int _index = _data.IndexOf("\r\n\r\n");
                if (_index == -1)
                {
                    _packageSize = 0; return(null);
                }
                if (!_completely && _index > -1)
                {
                    _packageSize = 0; return(new WstpPackage(WstpPackageType.Init));
                }

                _packageSize = uint.Parse((_index + 4).ToString());
                string[] _lines = _data.Split("\r\n");
                Dictionary <string, string> _header = new Dictionary <string, string>();
                foreach (string _line in _lines)
                {
                    string _key   = "";
                    string _value = "";
                    if (_line.StartsWith("GET"))
                    {
                        _key   = "Path";
                        _value = _line.Substring(4, _line.IndexOf(" ", 4) - 4);
                    }
                    else
                    {
                        int _splitIndex = _line.IndexOf(":");
                        if (_splitIndex == -1)
                        {
                            continue;
                        }
                        _key   = _line.Substring(0, _splitIndex).Trim();
                        _value = _line.Substring(_splitIndex + 1).Trim();
                    }
                    if (_header.ContainsKey(_key))
                    {
                        _header[_key] = _header[_key] + "\n" + _value;
                    }
                    else
                    {
                        _header.Add(_key, _value);
                    }
                }
                if (!_header.ContainsKey("Upgrade") || _header["Upgrade"] != "websocket")
                {
                    _packageSize = 0; _session.Disconnect(); return(null);
                }

                if (_header.ContainsKey("Sec-WebSocket-Key"))
                {
                    string _wsKey = _header["Sec-WebSocket-Key"];
                    if (_wsKey == "")
                    {
                        _packageSize = 0; _session.Dispose(); return(null);
                    }
                    string _wsSecret = SHA.EncodeSHA1ToBase64(_wsKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");

                    string _returnData = $"HTTP/1.1 101 Switching Protocols\r\n";
                    _returnData += $"Connection:Upgrade\r\n";
                    _returnData += $"Server:{this.name}\r\n";
                    _returnData += $"Upgrade:WebSocket\r\n";
                    _returnData += $"Date:{DateTime.UtcNow.ToString("r")}\r\n";
                    _returnData += $"Sec-WebSocket-Accept:{_wsSecret}\r\n\r\n";

                    _session.SendBytes(Encoding.UTF8.GetBytes(_returnData));
                    foreach (KeyValuePair <string, string> _item in _header)
                    {
                        _session[$"{_item.Key}"] = _item.Value;
                    }
                    _session["Sec-WebSocket-Secret"] = _wsSecret;
                    _session["__I__N__I__T__"]       = true;
                    return(new WstpPackage(WstpPackageType.Init));
                }
                else if (_header.ContainsKey("Sec-WebSocket-Key1"))
                {
                    string _origin = _header["Origin"];
                    if (_origin.Length == 0)
                    {
                        _origin = "null";
                    }

                    string _returnData = $"HTTP/1.1 101 Web Socket Protocol Handshake\r\n";
                    _returnData += $"Upgrade:WebSocket\r\n";
                    _returnData += $"Connection:Upgrade\r\n";
                    _returnData += $"Server:{this.name}\r\n";
                    _returnData += $"Date:{DateTime.UtcNow.ToString("r")}\r\n";
                    _returnData += $"Sec-WebSocket-Origin:{_origin}\r\n\r\n";
                    _returnData += $"Sec-WebSocket-Location:ws://{_header["Host"]}{_header["Path"]}\r\n\r\n";

                    uint _key1 = GetWebSocketKeyValue(_header["Sec-WebSocket-Key1"]);
                    uint _key2 = GetWebSocketKeyValue(_header["Sec-WebSocket-Key2"]);

                    string _keyExt = _lines[_lines.Length - 1];
                    if (_keyExt.Length < 8)
                    {
                        _packageSize = 0; _session.Disconnect(); return(null);
                    }

                    byte[] _buffer      = new byte[16];
                    byte[] _key1Bytes   = BitConverter.GetBytes(_key1);
                    byte[] _key2Bytes   = BitConverter.GetBytes(_key2);
                    byte[] _keyExtBytes = Encoding.UTF8.GetBytes(_keyExt);
                    Array.Copy(_key1Bytes, 0, _buffer, 0, _key1Bytes.Length);
                    Array.Copy(_key2Bytes, 0, _buffer, _key2Bytes.Length, _key2Bytes.Length);
                    Array.Copy(_keyExtBytes, 0, _buffer, _key1Bytes.Length + _key2Bytes.Length, _keyExtBytes.Length);
                    _returnData += Encrypt.MD5.Encode(_buffer);

                    _session.SendBytes(Encoding.UTF8.GetBytes(_returnData));
                    foreach (KeyValuePair <string, string> _item in _header)
                    {
                        _session[$"{_item.Key}"] = _item.Value;
                    }
                    _session["__I__N__I__T__"] = true;
                    return(new WstpPackage(WstpPackageType.Init));
                }
                #endregion
            }

            int _start = 0;
            _packageSize = 0;
            WstpPackage _package = null;
            if (_byteArray.Length == 0)
            {
                return(_package);
            }

            while (true)
            {
                int _fin = (_byteArray[_start] & 0x80) == 0x80 ? 1 : 0;
                if (_fin == 0)
                {
                    break;
                }

                int _op  = _byteArray[_start] & 0x0F;
                int _len = _byteArray[_start + 1] & 0x7F;

                int _lenByByte  = 1;
                int _maskByByte = 4;
                if (_len == 126)
                {
                    _lenByByte = 3;
                }
                else if (_len == 127)
                {
                    _lenByByte = 9;
                }
                if ((_byteArray.Length - _start) < (1 + _lenByByte + _maskByByte))
                {
                    break;
                }
                if (_len == 126)
                {
                    byte[] _buffer = new byte[2];
                    Array.Copy(_byteArray, _start + 2, _buffer, 0, _buffer.Length);
                    _len = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(_buffer, 0));
                }
                else if (_len == 127)
                {
                    byte[] _buffer = new byte[8];
                    Array.Copy(_byteArray, _start + 2, _buffer, 0, _buffer.Length);
                    _len = (int)System.Net.IPAddress.NetworkToHostOrder((long)BitConverter.ToInt64(_buffer, 0));
                }
                if ((_byteArray.Length - _start) < (1 + _lenByByte + _maskByByte + _len))
                {
                    break;
                }

                if (_op == 8)
                {
                    _session.SendPackage(new WstpPackage(WstpPackageType.Close));
                    _session.Disconnect();
                    _package = new WstpPackage(WstpPackageType.Close);
                }
                else if (_op == 9)
                {
                    _session.SendPackage(new WstpPackage(WstpPackageType.Pong));
                    _package = new WstpPackage(WstpPackageType.Ping);
                }

                byte[] _mask = new byte[_maskByByte];
                Array.Copy(_byteArray, _start + 1 + _lenByByte, _mask, 0, _maskByByte);
                byte[] _payload = new byte[_len];
                Array.Copy(_byteArray, _start + 1 + _lenByByte + _maskByByte, _payload, 0, _len);

                if (_package == null && _op == 1)
                {
                    _package = new WstpPackage(WstpPackageType.Text);
                }
                if (_package == null && _op == 2)
                {
                    _package = new WstpPackage(WstpPackageType.Binary);
                }
                if (_package == null)
                {
                    return(null);
                }

                int _binaryLen = _package.Binary.Length;
                Array.Resize(ref _package.Binary, _package.Binary.Length + _payload.Length);
                for (int i = 0; i < _payload.Length; i++)
                {
                    _package.Binary[_binaryLen + i] = (byte)(_payload[i] ^ _mask[i % 4]);
                }
                _start = _start + 1 + _lenByByte + _maskByByte + _len;
                if (_fin == 1)
                {
                    break;
                }
            }

            _packageSize = uint.Parse(_start.ToString());
            return(_package);
        }
Ejemplo n.º 13
0
        public bool Check(byte[] _byteArray, bool _completely = false, SocketSession _session = null)
        {
            if (_byteArray.Length < 20)
            {
                return(false);
            }

            byte[] _lengthArray = new byte[4];
            Array.Copy(_byteArray, _lengthArray, 4);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(_lengthArray);
            }
            int _packageSize = BitConverter.ToInt32(_lengthArray, 0);

            if (_byteArray.Length < _packageSize)
            {
                return(false);
            }

            string _key = "";

            if (_session == null)
            {
                _key = this.socketRxKey == "" ? this.socketKey : this.socketRxKey;
            }
            else
            {
                _key = (_session["RxKey"] + "") == "" ? this.socketKey : (_session["RxKey"] + "");
            }
            if (_key == "")
            {
                throw new Exception("DePackage failed: RxKey is empty.");
            }

            byte[] _checkArray = new byte[_packageSize - 16];
            Array.Copy(_byteArray, _checkArray, _checkArray.Length);
            string _check = System.Text.Encoding.UTF8.GetString(MD5.Encode2ByteArray(_checkArray));

            byte[] _md5Array = new byte[16];
            Array.Copy(_byteArray, _packageSize - 16, _md5Array, 0, 16);
            string _md5 = System.Text.Encoding.UTF8.GetString(_md5Array);

            if (_session != null && _session.Protocol == null)
            {
                try
                {
                    byte[] _contentArray = new byte[_packageSize - 20];
                    Array.Copy(_byteArray, 4, _contentArray, 0, _contentArray.Length);
                    string  _decoded = System.Text.Encoding.UTF8.GetString(DES.Decode2ByteArray(_contentArray, _key, System.Security.Cryptography.CipherMode.CBC));
                    JObject _json    = JObject.Parse(_decoded);
                    return(true);
                }
                catch
                {
                    return(false);
                }
            }
            else
            {
                return(_check == _md5);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 数据打包
        /// </summary>
        /// <param name="_objects">需要打包的对象</param>
        /// <returns>打包后的数据</returns>
        public byte[] EnPackage(object _object, SocketSession _session = null)
        {
            if (_object == null)
            {
                return(new byte[0]);
            }

            LztpPackage _package = (LztpPackage)_object;

            if (_package.TimestampSend == 0)
            {
                _package.TimestampSend = this.GetTimestamp(DateTime.UtcNow);
            }
            else
            {
                _package.TimestampResponse = this.GetTimestamp(DateTime.UtcNow);
            }

            MemoryStream _body_stream = new MemoryStream();

            byte[] _body_Fields = new byte[_package.Fields.Length];

            #region Body_Fields,Body_Content
            for (int i = 0; i < _package.Fields.Length; i++)
            {
                _body_Fields[i] = this.AppendToByteArray(ref _body_stream, _package.Fields[i]);
            }
            byte[] _body_Content = _body_stream.ToArray();
            _body_stream.Close();
            #endregion

            byte[] _body_Header = new byte[13 + _body_Fields.Length];
            #region Body_Header
            _body_Header[0] = 0x00;
            Array.Copy(this.UInt32ToByteArray(UInt32.Parse(_body_Content.Length.ToString())), 0, _body_Header, 1, 4);
            Array.Copy(this.UInt32ToByteArray(this.GetCRC32(_body_Content)), 0, _body_Header, 5, 4);
            Array.Copy(this.UInt32ToByteArray(UInt32.Parse(_package.Fields.Length.ToString())), 0, _body_Header, 9, 4);
            Array.Copy(_body_Fields, 0, _body_Header, 13, _body_Fields.Length);
            #endregion

            byte[] _packageArray = new byte[64 + _body_Header.Length + _body_Content.Length];
            byte[] _head_Content = new byte[60];
            #region Head_Content
            Array.Copy(this.Head, 0, _head_Content, 0, 4);
            Array.Copy(this.UInt32ToByteArray(_package.Version), 0, _head_Content, 4, 4);
            Array.Copy(this.UInt32ToByteArray(UInt32.Parse(_packageArray.Length.ToString())), 0, _head_Content, 8, 4);
            Array.Copy(this.UInt32ToByteArray(this.GetCRC32(_body_Header)), 0, _head_Content, 12, 4);
            Array.Copy(this.UInt16ToByteArray(_package.Command1), 0, _head_Content, 16, 2);
            Array.Copy(this.UInt16ToByteArray(_package.Command2), 0, _head_Content, 18, 2);
            Array.Copy(this.UInt32ToByteArray(_package.CommandId), 0, _head_Content, 20, 4);
            Array.Copy(this.DoubleToByteArray(_package.TimestampSend), 0, _head_Content, 24, 8);
            Array.Copy(this.DoubleToByteArray(_package.TimestampReceive), 0, _head_Content, 32, 8);
            Array.Copy(this.DoubleToByteArray(_package.TimestampResponse), 0, _head_Content, 40, 8);
            for (int i = 48; i < 60; i++)
            {
                _head_Content[i] = 0x0;
            }
            #endregion

            byte[] _head_CRC32 = new byte[4];
            #region Head_CRC32
            Array.Copy(this.UInt32ToByteArray(this.GetCRC32(_head_Content)), 0, _head_CRC32, 0, 4);
            #endregion

            Array.Copy(_head_Content, 0, _packageArray, 0, _head_Content.Length);
            Array.Copy(_head_CRC32, 0, _packageArray, _head_Content.Length, _head_CRC32.Length);
            Array.Copy(_body_Header, 0, _packageArray, _head_Content.Length + _head_CRC32.Length, _body_Header.Length);
            Array.Copy(_body_Content, 0, _packageArray, _head_Content.Length + _head_CRC32.Length + _body_Header.Length, _body_Content.Length);

            return(_packageArray);
        }
Ejemplo n.º 15
0
        internal void EndReceive(SocketAsyncEventArgs _socketAsyncEventArgs)
        {
            try
            {
                bool _disconnect = false;
                if (_socketAsyncEventArgs == null || _socketAsyncEventArgs.SocketError != SocketError.Success || _socketAsyncEventArgs.BytesTransferred <= 0 || _shutingdown)
                {
                    _disconnect = true;
                }

                SocketSession _socketSession = (SocketSession)_socketAsyncEventArgs.UserToken;
                if (!_disconnect)
                {
                    try
                    {
                        #region 读取数据
                        _socketSession.ReceivedStream.Write(_socketAsyncEventArgs.Buffer, _socketAsyncEventArgs.Offset, _socketAsyncEventArgs.BytesTransferred);
                        byte[] _receivedBytes = _socketSession.ReceivedStream.ToArray();
                        if (_receivedBytes == null)
                        {
                            _disconnect = true;
                        }
                        try
                        {
                            this.OnReceive(_socketSession, _receivedBytes);
                        }
                        catch (Exception _ex)
                        {
                            this.OnException(_ex);
                            _disconnect = true;
                        }
                        _socketSession.LastOperationTime = DateTime.UtcNow;
                        #endregion

                        #region 匹配协议
                        if (_socketSession.Protocol == null)
                        {
                            for (int i = 0; i < this.Protocols.Length; i++)
                            {
                                if (this.Protocols[i].Check(_receivedBytes, false, _socketSession))
                                {
                                    _socketSession.Protocol = this.Protocols[i];
                                    break;
                                }
                            }
                        }
                        #endregion

                        #region 处理数据包
                        if (_socketSession.Protocol != null)
                        {
                            while (_receivedBytes != null && _socketSession.Protocol.Check(_receivedBytes, false, _socketSession))
                            {
                                uint   _packageSize = 0;
                                object _package     = _socketSession.Protocol.DePackage(_receivedBytes, out _packageSize, false, _socketSession);
                                if (_package == null)
                                {
                                    throw new Exception("Package is NULL.");
                                }

                                #region OnReceivingPackage 事件处理
                                try
                                {
                                    this.OnReceivingPackage(_socketSession, _package);
                                }
                                catch (Exception _ex)
                                {
                                    this.OnException(_ex);
                                }
                                #endregion

                                if (!_socketSession.Protocol.Check(_receivedBytes, true, _socketSession))
                                {
                                    break;
                                }

                                _packageSize = 0;
                                _package     = _socketSession.Protocol.DePackage(_receivedBytes, out _packageSize, true, _socketSession);
                                if (_package == null)
                                {
                                    throw new Exception("Package is NULL.");
                                }

                                #region 刷新已接受数据流
                                byte[] _temp = new byte[_socketSession.ReceivedStream.Length - _packageSize];
                                if (_temp.Length > 0)
                                {
                                    _socketSession.ReceivedStream.Position = _packageSize;
                                    _socketSession.ReceivedStream.Read(_temp, 0, _temp.Length);
                                    _socketSession.ReceivedStream.Position = 0;
                                    _socketSession.ReceivedStream.Write(_temp, 0, _temp.Length);
                                    _socketSession.ReceivedStream.SetLength(_temp.Length);
                                    _socketSession.ReceivedStream.Capacity = _temp.Length;
                                    _receivedBytes = _socketSession.ReceivedStream.ToArray();
                                }
                                else
                                {
                                    _socketSession.ReceivedStream.SetLength(0);
                                    _socketSession.ReceivedStream.Capacity = 0;
                                    _receivedBytes = new byte[0];
                                }
                                #endregion

                                #region OnReceivedPackage 事件处理
                                try
                                {
                                    if (_socketSession.Protocol.IsKeepAlivePackage(_package, _socketSession))
                                    {
                                        _socketSession.SendPackage(_socketSession.Protocol.KeepAlivePackage);
                                    }
                                    else
                                    {
                                        this.OnReceivedPackage(_socketSession, _package);
                                    }
                                }
                                catch (Exception _ex)
                                {
                                    this.OnException(_ex);
                                }
                                #endregion
                            }
                        }
                        #endregion

                        this.BeginReceive(_socketAsyncEventArgs);
                        return;
                    }
                    catch (Exception _ex)
                    {
                        Console.WriteLine(_ex);
                        _disconnect = true;
                    }
                }

                if (_disconnect)
                {
                    this.BeginDisconnect(_socketAsyncEventArgs.AcceptSocket);
                    this.OnSessionEnd(_socketSession);
                    this.bufferManager.FreeBuffer(_socketAsyncEventArgs);
                    _socketSession.Clear();
                }
            }
            catch (Exception _ex)
            {
                this.OnException(_ex);
            }
        }
Ejemplo n.º 16
0
        public object DePackage(byte[] _byteArray, out uint _packageSize, bool _completely = false, SocketSession _session = null)
        {
            string _data = Encoding.UTF8.GetString(_byteArray);

            int _index = _data.IndexOf('\n');

            _packageSize = uint.Parse((_index + 1).ToString());
            if (_index <= -1)
            {
                return(null);
            }

            try
            {
                string _source = _data.Substring(0, _index);
                return(JObject.Parse(OpenSSLAes.Decode(_source, this.key)));
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 实现接口:是否是一个完整的包
        /// </summary>
        /// <param name="_byteArray">检查的数据流</param>
        /// <param name="_completely">是否完全检查数据包</param>
        /// <returns>是否检测成功</returns>
        public bool Check(byte[] _byteArray, bool _completely, SocketSession _session = null)
        {
            // 检查读取头大小
            if (_byteArray == null || _byteArray.Length < 64)
            {
                return(false);
            }
            if (_byteArray[0] != this.Head[0] || _byteArray[1] != this.Head[1] || _byteArray[2] != this.Head[2] || _byteArray[3] != this.Head[3])
            {
                return(false);
            }

            // 读取头部信息
            byte[] _packageHeader = new byte[64];
            Array.Copy(_byteArray, 0, _packageHeader, 0, 64);

            byte[] _packageLengthArray = new byte[4];
            Array.Copy(_packageHeader, 8, _packageLengthArray, 0, 4);
            uint _packageLength = this.ByteArrayToUInt32(_packageLengthArray);

            byte[] _packageHeaderCRC32 = new byte[4];
            Array.Copy(_packageHeader, 60, _packageHeaderCRC32, 0, 4);

            // 检查头部CRC32
            byte[] _packageHeaderContent = new byte[60];
            Array.Copy(_packageHeader, 0, _packageHeaderContent, 0, 60);
            if (this.GetCRC32(_packageHeaderContent) != this.ByteArrayToUInt32(_packageHeaderCRC32))
            {
                return(false);
            }

            // 检查数据头CRC32
            try
            {
                if (_completely && _packageLength > uint.Parse("64"))
                {
                    if (uint.Parse(_byteArray.Length.ToString()) < _packageLength)
                    {
                        return(false);
                    }

                    byte _packageBodyType = _byteArray[64];

                    byte[] _packageBodyLengthArray = new byte[4];
                    Array.Copy(_byteArray, 65, _packageBodyLengthArray, 0, 4);
                    uint _packageBodyLength = this.ByteArrayToUInt32(_packageBodyLengthArray);

                    byte[] _packageBodyCRC32Array = new byte[4];
                    Array.Copy(_byteArray, 69, _packageBodyCRC32Array, 0, 4);
                    uint _packageBodyCRC32 = this.ByteArrayToUInt32(_packageBodyCRC32Array);

                    byte[] _packageBodyFieldCountArray = new byte[4];
                    Array.Copy(_byteArray, 73, _packageBodyFieldCountArray, 0, 4);
                    uint _packageBodyFieldCount = this.ByteArrayToUInt32(_packageBodyFieldCountArray);

                    byte[] _packageBodyArray = new byte[_packageBodyLength];
                    Array.Copy(_byteArray, (long)(77 + _packageBodyFieldCount), _packageBodyArray, 0, _packageBodyLength);
                    if (this.GetCRC32(_packageBodyArray) != _packageBodyCRC32)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 18
0
        public object DePackage(byte[] _byteArray, out uint _packageSize, bool _completely, SocketSession _session = null)
        {
            if (!this.Check(_byteArray, _completely, _session))
            {
                throw new Exception("Can not depackage this stream.");
            }

            string _key = "";

            if (_session == null)
            {
                _key = this.socketRxKey == "" ? this.socketKey : this.socketRxKey;
            }
            else
            {
                _key = (_session["RxKey"] + "") == "" ? this.socketKey : (_session["RxKey"] + "");
            }
            if (_key == "")
            {
                throw new Exception("DePackage failed: RxKey is empty.");
            }

            byte[] _lengthArray = new byte[4];
            Array.Copy(_byteArray, _lengthArray, 4);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(_lengthArray);
            }
            _packageSize = BitConverter.ToUInt32(_lengthArray, 0);

            try
            {
                byte[] _contentArray = new byte[_packageSize - 20];
                Array.Copy(_byteArray, 4, _contentArray, 0, _contentArray.Length);
                string  _decoded = System.Text.Encoding.UTF8.GetString(DES.Decode2ByteArray(_contentArray, _key, System.Security.Cryptography.CipherMode.CBC));
                JObject _json    = JObject.Parse(_decoded);
                return(_json);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 数据解包
        /// </summary>
        /// <param name="_byteArray">解包的数据流</param>
        /// <param name="_packageSize">输出数据包整体大小</param>
        /// <returns>解包后的对象</returns>
        public object DePackage(byte[] _byteArray, out uint _packageSize, bool _completely, SocketSession _session = null)
        {
            if (!this.Check(_byteArray, _completely))
            {
                throw new Exception("Can not depackage this stream.");
            }

            LztpPackage _package = new LztpPackage();

            byte[] _packageHeader = new byte[64];
            Array.Copy(_byteArray, 0, _packageHeader, 0, 64);
            byte[] _packageVersion = new byte[4];
            Array.Copy(_packageHeader, 4, _packageVersion, 0, 4);
            byte[] _packageLength = new byte[4];
            Array.Copy(_packageHeader, 8, _packageLength, 0, 4);
            byte[] _packageBodyCRC32 = new byte[4];
            Array.Copy(_packageHeader, 12, _packageBodyCRC32, 0, 4);
            byte[] _packageCommand1 = new byte[2];
            Array.Copy(_packageHeader, 16, _packageCommand1, 0, 2);
            byte[] _packageCommand2 = new byte[2];
            Array.Copy(_packageHeader, 18, _packageCommand2, 0, 2);
            byte[] _packageCommandId = new byte[4];
            Array.Copy(_packageHeader, 20, _packageCommandId, 0, 4);
            byte[] _packageTimestampSend = new byte[8];
            Array.Copy(_packageHeader, 24, _packageTimestampSend, 0, 8);
            byte[] _packageTimestampReceive = new byte[8];
            Array.Copy(_packageHeader, 32, _packageTimestampReceive, 0, 8);
            byte[] _packageTimestampResponse = new byte[8];
            Array.Copy(_packageHeader, 40, _packageTimestampResponse, 0, 8);
            byte[] _packageHeaderCRC32 = new byte[4];
            Array.Copy(_packageHeader, 60, _packageHeaderCRC32, 0, 4);

            _package.Version           = this.ByteArrayToUInt32(_packageVersion);
            _package.Length            = this.ByteArrayToUInt32(_packageLength);
            _package.BodyHeadCRC32     = this.ByteArrayToUInt32(_packageBodyCRC32);
            _package.Command1          = this.ByteArrayToUInt16(_packageCommand1);
            _package.Command2          = this.ByteArrayToUInt16(_packageCommand2);
            _package.CommandId         = this.ByteArrayToUInt32(_packageCommandId);
            _package.TimestampSend     = this.ByteArrayToDouble(_packageTimestampSend);
            _package.TimestampReceive  = this.GetTimestamp(DateTime.Now);
            _package.TimestampResponse = this.ByteArrayToDouble(_packageTimestampResponse);
            _package.HeadCRC32         = this.ByteArrayToUInt32(_packageHeaderCRC32);
            _package.BodyType          = new byte();
            _package.BodyLength        = 0;
            _package.BodyCRC32         = 0;
            _package.FieldCount        = 0;
            _package.Fields            = new object[0];
            _package.FieldTypes        = new byte[0];

            _package.ReceivedLength = _byteArray.Length - 64;
            if (_package.ReceivedLength > _package.Length - 64)
            {
                _package.ReceivedLength = int.Parse(_package.Length.ToString()) - 64;
            }

            if (_completely && _package.Length > 64)
            {
                _package.BodyType = _byteArray[64];
                //string _byteString = "";
                //for (int i = 0; i < _byteArray.Length; i++)
                //{
                //    _byteString += i > 0 && i % 8 == 0 ? "\n" : "";
                //    _byteString += _byteArray[i].ToString("X2") + " ";
                //}
                if (_package.BodyType == 0x00)
                {
                    #region 0x00 数据包
                    byte[] _bodyLength = new byte[4];
                    Array.Copy(_byteArray, 65, _bodyLength, 0, 4);
                    _package.BodyLength = this.ByteArrayToUInt32(_bodyLength);

                    byte[] _bodyCRC32 = new byte[4];
                    Array.Copy(_byteArray, 69, _bodyCRC32, 0, 4);
                    _package.BodyCRC32 = this.ByteArrayToUInt32(_bodyCRC32);

                    byte[] _fieldCount = new byte[4];
                    Array.Copy(_byteArray, 73, _fieldCount, 0, 4);
                    _package.FieldCount = this.ByteArrayToUInt32(_fieldCount);

                    byte[] _fieldTypes = new byte[_package.FieldCount];
                    Array.Copy(_byteArray, 77, _fieldTypes, 0, _fieldTypes.Length);
                    _package.FieldTypes = _fieldTypes;
                    if (_package.FieldCount != _package.FieldTypes.Length)
                    {
                        throw new Exception("Field count and type length not match.");
                    }
                    if (_package.FieldCount > 100000)
                    {
                        throw new Exception("Field count can not more then 100000.");
                    }

                    _package.Fields = new object[_package.FieldCount];
                    uint _position  = 77 + (uint)_package.FieldTypes.Length;
                    uint _fieldSize = 0;
                    for (UInt32 i = 0; i < _fieldTypes.Length; i++)
                    {
                        _package.Fields[i] = this.GetFromByteArray(_byteArray, _position, _package.FieldTypes[i], ref _fieldSize);
                        _position         += _fieldSize;
                    }
                    #endregion
                }
                else if (_package.BodyType == 0x01)
                {
                    _packageSize = 0;
                }
            }

            _packageSize = _package.Length;
            return(_package);
        }
Ejemplo n.º 20
0
 public bool Check(byte[] _byteArray, bool _completely = false, SocketSession _session = null)
 {
     return(this.DePackage(_byteArray, out uint _package) != null);
 }