예제 #1
0
        public void TestTwoTitles()
        {
            var input          = new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 0, 1, 31, 139, 8, 0, 0, 0, 0, 0, 4, 0 };
            var buffer         = new BytesBuffer(input, 0, input.Length - 1);
            var portion        = new ArhivePortion(buffer);
            var firstExtracted = portion.ExtractFirstTitleAndData();

            Assert.IsNotNull(firstExtracted, "firstExtracted == null");
            Assert.AreEqual(0, firstExtracted.StartPosition, "firstExtracted.StartPosition");
            Assert.AreEqual(10, firstExtracted.EndPosition, "firstExtracted.EndPosition");
            Assert.AreEqual(11, firstExtracted.Size, "firstExtracted.Size");

            Assert.IsFalse(portion.IsEmpty, "portion.IsEmpty");
            Assert.IsTrue(portion.IsExistsTitle, "portion.IsExistsTitle");

            var secondExtracted = portion.ExtractFirstTitleAndData();

            Assert.IsNotNull(secondExtracted, "secondExtracted == null");
            Assert.AreEqual(11, secondExtracted.StartPosition, "secondExtracted.StartPosition");
            Assert.AreEqual(20, secondExtracted.EndPosition, "secondExtracted.EndPosition");
            Assert.AreEqual(10, secondExtracted.Size, "secondExtracted.Size");

            Assert.IsTrue(portion.IsEmpty, "portion.IsEmpty");
            Assert.IsFalse(portion.IsExistsTitle, "portion.IsExistsTitle");
        }
예제 #2
0
    public void AddBytesBuffer(BytesBuffer bb)
    {
        int bbLength = bb.GetOffset();

        //Debug.Log("bbLength = " + bbLength);
        AddInt(bbLength);
        AddBytes(bb.GetBytes(), bbLength);
    }
예제 #3
0
    public void SaveData(BinaryWriter bw)
    {
        BytesBuffer bb       = SaveBytesBuffer();
        int         bbLength = bb.GetOffset();

        bw.Write(bbLength);
        bw.Write(bb.GetBytes(), 0, bbLength);
    }
예제 #4
0
        public void TestOneByte()
        {
            var buffer = new BytesBuffer(new byte[] { 1 }, 0, 0);

            Assert.AreEqual(0, buffer.StartPosition, "StartPosition");
            Assert.AreEqual(0, buffer.EndPosition, "EndPosition");
            Assert.AreEqual(1, buffer.Size, "Size");
        }
예제 #5
0
    public BytesBuffer SaveBytesBuffer()
    {
        BytesBuffer saveDataBuffer = new BytesBuffer(1024);

        saveDataBuffer.AddString(LocalSaveData.LoginUserName);
        saveDataBuffer.AddString(LocalSaveData.LoginPassword);
        return(saveDataBuffer);
    }
예제 #6
0
    public void LoadData(BinaryReader br)
    {
        int bufferLength = br.ReadInt32();

        byte[]      bufferData = br.ReadBytes(bufferLength);
        BytesBuffer bb         = new BytesBuffer(bufferData);

        LoadBytesBuffer(bb);
    }
예제 #7
0
        public async Task ShouldWaitForFilledSectionInEmptyBuffer()
        {
            // Given
            var buffer = new BytesBuffer(PageSize);

            // When
            var task = buffer.GetFilledSegmentAsync(_token);

            // Then
            await AsyncAssert.NeverCompletesAsync(task);
        }
예제 #8
0
    public void Send()
    {
        if (sendBuffer == null)
        {
            //typeof(this);// this.GetType ();
            sendBuffer = new BytesBuffer(512);
        }

        serialize();

        NetSystem.getInstance().sendCmd(this);
    }
예제 #9
0
        public async Task ShouldGetCorrectOneFreeSegment()
        {
            // Given
            var bufferSize = PageSize / 2;
            var buffer     = new BytesBuffer(bufferSize);

            // When
            var segment1 = await buffer.GetEmptySegmentAsync(_token);

            // Then
            segment1.Count.ShouldBe(bufferSize);
            segment1.Offset.ShouldBe(0);
        }
예제 #10
0
        public void DataBeforePartTitle()
        {
            var input     = new byte[] { 1, 31, 139, 8, 0, 0, 0 };
            var buffer    = new BytesBuffer(input, 0, input.Length - 1);
            var portion   = new ArhivePortion(buffer);
            var extracted = portion.ExtractDataBeforeTitle();

            Assert.IsNotNull(extracted, "extracted == null");
            Assert.AreEqual(0, extracted.StartPosition, "extracted.StartPosition");
            Assert.AreEqual(0, extracted.EndPosition, "extracted.EndPosition");
            Assert.AreEqual(1, extracted.Size, "extracted.Size");

            Assert.IsTrue(portion.IsNotEmpty, "portion.IsNotEmpty");
            Assert.IsTrue(portion.IsExistsTitle, "portion.IsExistsTitle");
        }
예제 #11
0
    public bool dispatchPacket(BytesBuffer _buffer)
    {
        MESSAGE_COUNT = m_messageQueue.Count;
        if (MESSAGE_COUNT > MAX_MESSAGE_QUEUE_LENGTH)
        {
            Debug.LogError("超出最大消息队列长度");
            return(false);
        }

        //将数据插入消息队列
        m_messageQueue.Enqueue(_buffer);

        //processPacket ();

        return(true);
    }
예제 #12
0
        public async Task ShouldChangeSegmentSize()
        {
            // Given
            var buffer  = new BytesBuffer(PageSize);
            var newSize = 100;

            // When
            var segment = await buffer.GetEmptySegmentAsync(_token);

            await buffer.FillSegmentAsync(segment, newSize, _token);

            var filledSegment = await buffer.GetFilledSegmentAsync(_token);

            // Then
            filledSegment.Count.ShouldBe(newSize);
        }
예제 #13
0
        public async Task ShouldWaitForFilledSegment()
        {
            // Given
            var buffer = new BytesBuffer(PageSize);

            // When
            var segment = await buffer.GetEmptySegmentAsync(_token);

            await buffer.FillSegmentAsync(segment, segment.Count, _token);

            var filledSegment = await buffer.GetFilledSegmentAsync(_token);

            var task = buffer.GetFilledSegmentAsync(_token);

            // Then
            await AsyncAssert.NeverCompletesAsync(task);
        }
예제 #14
0
        public void TestAppendPartTitle()
        {
            var first       = new byte[] { 31, 139, 8, 0, 0 };
            var firstBuffer = new BytesBuffer(first, 0, first.Length - 1);
            var portion     = new ArhivePortion(firstBuffer);

            var second       = new byte[] { 0, 0, 0, 4, 0, 1 };
            var secondBuffer = new BytesBuffer(second, 0, second.Length - 1);

            portion.Append(secondBuffer);

            Assert.IsTrue(portion.IsExistsAllTitle, "порция должна содержать title");
            var titleAndData = portion.ExtractFirstTitleAndData();

            Assert.AreEqual(0, titleAndData.StartPosition, "titleAndData.StartPosition");
            Assert.AreEqual(11, titleAndData.Size, "titleAndData.StartPosition");
            Assert.IsTrue(titleAndData.InnerBuffer.SequenceEqual(new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 0, 1 }),
                          "неверный titleAndData");
        }
예제 #15
0
        public BytesBuffer ProcessResponse(byte[] data, int offset, int count)
        {
            AMessage message = reader.Process(data, offset, count);

            if (message == null)
            {
                return(null);
            }

            AMessage result = GetResponse(message);

            if (result == null)
            {
                return(null);
            }

            BytesBuffer bb = new BytesBuffer(128);

            result.Serialize(bb);
            return(bb);
        }
예제 #16
0
    //发送协议并加锁,防止连续多次发送协议,必须收到指定协议之后才可继续发送协议
    public bool sendCmd_And_Lock(BaseCmd _cmd, int _unLockKey)
    {
        if (_cmd.getSize() <= 0 || !m_isConnected || m_sendLock)
        {
            return(false);
        }

        int         _message_length = _cmd.getSize() + 4;
        BytesBuffer _sendBuf        = new BytesBuffer(_message_length);

        _sendBuf.writeInt32(_message_length - 4);

        System.Buffer.BlockCopy(_cmd.getBuffer.bytes, 0, _sendBuf.bytes, 4, _cmd.getSize());

        m_ClientSocket.Client.BeginSend(_sendBuf.bytes, 0, _sendBuf.bytes.Length, SocketFlags.None, new AsyncCallback(_onSendMsg), m_ClientSocket);

        m_sendUnLockKey = _unLockKey;
        m_sendLock      = true;

        return(true);
    }
예제 #17
0
    //发送协议
    public bool sendCmd(BaseCmd _cmd)
    {
        if (!m_isConnected)
        {
            Debug.LogErrorFormat("当前未连接服务器! {0}", DateTime.Now);
        }

        if (_cmd.getSize() <= 0 || !m_isConnected || m_sendLock)
        {
            Debug.LogWarning("send field");
            return(false);
        }

        // Debug.Log("[SEND] cmd : " + _cmd.Cmd.ToString() + " para :" + _cmd.Para.ToString() + " msgLength : " + _cmd.getSize().ToString());

        int _message_length = _cmd.getSize();
        //BytesBuffer _sendBuf = new BytesBuffer (_message_length);
        BytesBuffer _sendBuf = _cmd.sendBuffer;

        _sendBuf.resetPosition();
        _sendBuf.writeInt32(_message_length - 4);

        //System.Buffer.BlockCopy (_cmd.getBuffer.bytes, 0, _sendBuf.bytes, 4, _cmd.getSize());

        if (_sendAsyncCallback == null)
        {
            _sendAsyncCallback = new AsyncCallback(_onSendMsg);
        }
        //m_ClientSocket.Client.BeginSend (_sendBuf.bytes, 0, _sendBuf.bytes.Length, SocketFlags.None, _sendAsyncCallback, m_ClientSocket);

        m_ClientSocket.Client.Send(_sendBuf.bytes, 0, _message_length, SocketFlags.None);

        /* 断包测试
         * int bl = 5;
         * m_ClientSocket.Client.Send (_sendBuf.bytes, 0, _sendBuf.bytes.Length - bl, SocketFlags.None);
         * System.Threading.Thread.Sleep (1000);
         * m_ClientSocket.Client.Send (_sendBuf.bytes, bl, bl, SocketFlags.None);
         * ///*/
        return(true);
    }
예제 #18
0
        public async Task ShouldGetCorrectFreeSegments()
        {
            // Given
            var bufferSize       = 10000;
            var lastSegmentCount = bufferSize - PageSize * 2;
            var buffer           = new BytesBuffer(bufferSize);

            // When
            var segment1 = await buffer.GetEmptySegmentAsync(_token);

            var segment2 = await buffer.GetEmptySegmentAsync(_token);

            var segment3 = await buffer.GetEmptySegmentAsync(_token);

            // Then
            segment1.Count.ShouldBe(PageSize);
            segment1.Offset.ShouldBe(0);
            segment2.Count.ShouldBe(PageSize);
            segment2.Offset.ShouldBe(PageSize);
            segment3.Count.ShouldBe(lastSegmentCount);
            segment3.Offset.ShouldBe(PageSize * 2);
        }
예제 #19
0
    void DispenseMsg()
    {
        //解析消息的协议头
        BytesBuffer _msgBuffer = m_messageQueue.Dequeue();

        if (_msgBuffer.bytes.Length < 4)
        {
            m_isPacketProcessing = false;
            MESSAGE_COUNT        = m_messageQueue.Count;

            Debug.LogError("收到错误的协议,抛弃");
            return;
        }
        byte _cmd    = _msgBuffer.readByte();
        byte _para   = _msgBuffer.readByte();
        uint _dwTime = _msgBuffer.readUInt32();

        Debug.Log("[RECV]cmd :" + _cmd.ToString() + "   para : " + _para.ToString());

        if (_cmd == 2 && _para == 15)
        {
            //心跳协议 不需要处理
            RecvHeartCmd();
            return;
        }


        if (NetSystem.getInstance().GetSendLock)
        {
            //发送加锁 需要判断收到的消息是否可以进行解锁
            if (GET_MESSAGE_KEY(_cmd, _para) == NetSystem.getInstance().GetUnLockKey)
            {
                NetSystem.getInstance().sendUnLock();
            }
        }

        StartCoroutine(TriigerEvent(GET_MESSAGE_KEY(_cmd, _para), _cmd, _para, _msgBuffer));
    }
예제 #20
0
		private bool UnpackCollectionLength( Stream source, UnpackingMode unpackingMode, out MessagePackObject? unpacked )
		{
			int feeded;
			this._bytesBuffer = this._bytesBuffer.Feed( source, out feeded );
			this._readByteLength += feeded;

			if ( this._bytesBuffer.IsFilled )
			{
				// new collection

				var length = this._bytesBuffer.AsUInt32();
				if ( length == 0 )
				{
					// empty collection
					if ( unpackingMode == UnpackingMode.SkipSubtree )
					{
						// Set dummy
						unpacked = MessagePackObject.Nil;
					}
					else
					{
						unpacked = CreateEmptyCollection( this._contextValueHeader );
					}

					this._lastEmptyCollection = ToEmptyCollectionType( this._contextValueHeader.Type );
					return true;
				}

				this._collectionState.NewContextCollection( this._contextValueHeader, length );
				this.TransitToUnpackContextCollection();

				unpacked = null;
				return true;
			}

			// Try next iteration.
			unpacked = null;
			return false;
		}
예제 #21
0
 public void LoadBytesBuffer(BytesBuffer bb)
 {
     LocalSaveData.LoginUserName = bb.ReadString();
     LocalSaveData.LoginPassword = bb.ReadString();
 }
예제 #22
0
		private bool UnpackRawLength( Stream source, UnpackingMode unpackingMode, out MessagePackObject? unpacked )
		{
			int feeded;
			this._bytesBuffer = this._bytesBuffer.Feed( source, out feeded );
			this._readByteLength += feeded;

			if ( this._bytesBuffer.IsFilled )
			{
				var length = this._bytesBuffer.AsUInt32();
				if ( length == 0 )
				{
					// empty collection
					if ( unpackingMode == UnpackingMode.SkipSubtree )
					{
						// Set dummy
						unpacked = MessagePackObject.Nil;
					}
					else
					{
						unpacked = CreateEmptyCollection( this._contextValueHeader );
					}

					// Empty raw is not considered as EmptyCollection.
					return true;
				}

				this.TransitToUnpackRawBytes( length );

				return this.UnpackRawBytes( source, unpackingMode, out unpacked );
			}

			// Need more info.
			unpacked = null;
			return false;
		}
예제 #23
0
		private bool UnpackRawBytes( Stream source, UnpackingMode unpackingMode, out MessagePackObject? unpacked )
		{
#if DEBUG
			Contract.Assert( this._bytesBuffer.BackingStore != null, this._bytesBuffer.ToString() );
#endif

			int feeded;
			this._bytesBuffer = this._bytesBuffer.Feed( source, out feeded );
			this._readByteLength += feeded;
			if ( this._bytesBuffer.IsFilled )
			{
				if ( unpackingMode == UnpackingMode.SkipSubtree )
				{
					// Set dummy
					unpacked = MessagePackObject.Nil;
				}
				else
				{
					unpacked = this._bytesBuffer.AsMessagePackObject( this._contextValueHeader.Type );
				}

				return true;
			}

			// Need more info.
			unpacked = null;
			return false;
		}
예제 #24
0
		/// <summary>
		///		Transit current stage to unpackRawBytes stage with cleanuping states.
		/// </summary>
		/// <param name="length">The known length of the source.</param>
		private void TransitToUnpackRawBytes( uint length )
		{
			this._next = this._unpackRawBytes;
			this._isInCollection = false;
			// Allocate buffer to store raw binaries.
			this._bytesBuffer = new BytesBuffer( length );
		}
예제 #25
0
		/// <summary>
		///		Transit current stage to unpackContextCollection stage with cleanuping states.
		/// </summary>
		private void TransitToUnpackContextCollection()
		{
			this._next = this._unpackHeader;
			this._isInCollection = true;
			this._contextValueHeader = MessagePackHeader.Null;
			this._bytesBuffer = BytesBuffer.Null;
		}