private bool AnalysisSystemMessage(Packet packet) { int dataStruct = Marshal.SizeOf(typeof(CMD_CS_MarqueeMessage)); if (packet.DataSize < dataStruct) { com.QH.QPGame.GameUtils.Logger.Net.LogError("CMD_CS_MarqueeMessage Data Error !"); return(true); } ByteBuffer listDataBuff = ByteBufferPool.PopPacket(packet.Data); int dataSzie = Marshal.SizeOf(typeof(CMD_CS_MarqueeMessage)); int dataCount = packet.DataSize / dataSzie; for (int i = 0; i < dataCount; i++) { byte[] tempData = listDataBuff.PopByteArray(dataSzie); CMD_CS_MarqueeMessage msg = GameConvert.ByteToStruct <CMD_CS_MarqueeMessage>(tempData); GameApp.Account.CallMarqueeMessageEvent(msg.MsgType, msg.MsgID, msg.MsgPlayCount, (float)msg.MsgInterval, msg.szMessage, msg.MsgStartTime, msg.MsgNumberID, msg.MsgPlayTime); } ByteBufferPool.DropPacket(listDataBuff); return(true); }
//游戏记录 private bool AnalysisGameRecord(Packet packet) { //int dataStruct = Marshal.SizeOf(typeof(CMD_GH_GameRecord)); //if (packet.DataSize < dataStruct) //{ // Debug.LogError("Game Record Data Error CMD_GH_GameRecord!"); // return false; //} List <GameRecordItem> gameRecordList = new List <GameRecordItem>(); if (packet.DataSize > 0) { ByteBuffer listDataBuff = ByteBufferPool.PopPacket(packet.Data); int dataSzie = Marshal.SizeOf(typeof(CMD_GH_GameRecord)); int dataCount = packet.DataSize / dataSzie; for (int i = 0; i < dataCount; i++) { byte[] tempData = listDataBuff.PopByteArray(dataSzie); CMD_GH_GameRecord gameRecord = GameConvert.ByteToStruct <CMD_GH_GameRecord>(tempData); GameRecordItem gameItem = new GameRecordItem(); gameItem.dwAllCount = gameRecord.dwAllCount; gameItem.dwAmount = gameRecord.dwAmount; gameItem.dwEndTime = gameRecord.dwEndTime; gameItem.dwGameKind = gameRecord.dwGameKind; gameRecordList.Add(gameItem); } ByteBufferPool.DropPacket(listDataBuff); } GameApp.Account.CallGameRecordEvent(gameRecordList); return(true); }
public void Setup() { _cbs = new MockSmartCallbacks(); _bareSock = new MockSock(); _bufferPool = new ByteBufferPool(); _sock = new SmartSock(_bufferPool, _bareSock, _cbs); }
protected override void Init() { _bufferPool = new ByteBufferPool(); _servSock = new SmartSock(_bufferPool, new ThreadSock(_bufferPool, AddressFamily.InterNetwork, new LoggerStub()), _soc); _servSock.Listen(2345); }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.NotSupportedException"/> public virtual ByteBuffer Read(ByteBufferPool bufferPool, int maxLength, EnumSet < ReadOption> opts) { CheckStream(); try { if (outBuffer.Remaining() > 0) { // Have some decrypted data unread, need to reset. ((Seekable)@in).Seek(GetPos()); ResetStreamOffset(GetPos()); } ByteBuffer buffer = ((HasEnhancedByteBufferAccess)@in).Read(bufferPool, maxLength , opts); if (buffer != null) { int n = buffer.Remaining(); if (n > 0) { streamOffset += buffer.Remaining(); // Read n bytes int pos = buffer.Position(); Decrypt(buffer, n, pos); } } return(buffer); } catch (InvalidCastException) { throw new NotSupportedException("This stream does not support " + "enhanced byte buffer access." ); } }
public void CorrectPoolingTest() { var pool = new ByteBufferPool(); var buf = pool.Get(5); pool.Return(buf); Assert.AreEqual(1, pool.FreeAmount); var buf2 = pool.Get(4); pool.Return(buf2); Assert.AreEqual(1, pool.FreeAmount); // ByteBufferPool removes a buffer when none of the buffers in the pool // is large enough to satisfy a Get, and it has at least 1 buffer in the pool. // This way the number of items in the pool does not grow beyond the number // of buffers that are in use simultaneously, lowering overall memory usage. // the following Get should remove the size 5 buffer from the pool because it is not in use var buf3 = pool.Get(6); pool.Return(buf3); Assert.AreEqual(1, pool.FreeAmount); buf3 = pool.Get(6); var buf4 = pool.Get(5); pool.Return(buf4); pool.Return(buf3); Assert.AreEqual(2, pool.FreeAmount); }
public void TestOverflow() { var buffer = new ByteBufferPool(10, new int[] { 1, 2, 3, 4 }); byte[] a = buffer.LeaseBytes(1); byte[] b = buffer.LeaseBytes(2); byte[] c = buffer.LeaseBytes(3); byte[] d = buffer.LeaseBytes(4); Assert.AreEqual(0, buffer.AllocatedBytes); buffer.ReturnBytes(a); Assert.AreEqual(1, buffer.AllocatedBytes); buffer.ReturnBytes(b); Assert.AreEqual(3, buffer.AllocatedBytes); buffer.ReturnBytes(c); Assert.AreEqual(6, buffer.AllocatedBytes); buffer.ReturnBytes(d); Assert.AreEqual(10, buffer.AllocatedBytes); byte[] e = buffer.LeaseBytes(4); buffer.ReturnBytes(e); Assert.AreEqual(10, buffer.AllocatedBytes); }
void HandleData(NetIncomingMessage message) { ushort id = ushort.MaxValue; ByteBuffer byteBuffer = null; try { id = message.ReadUInt16(); ushort len = message.ReadUInt16(); byteBuffer = ByteBufferPool.Alloc(len); message.ReadBytes(byteBuffer.Data, 0, len); var result = dispatcher.Fire(message.SenderConnection, (MessageID)id, byteBuffer, message); if (result != MessageHandleResult.Processing) { ByteBufferPool.Dealloc(ref byteBuffer); } } catch (Exception e) { ByteBufferPool.Dealloc(ref byteBuffer); NetLog.Exception("HandleData throws exception", e); if (id != ushort.MaxValue) { NetLog.Error("Caught exception when processing message " + (MessageID)id); } else { NetLog.Error("Caught exception when processing message"); } } }
public void MultiplePacketsSent() { UdpClient udpClient = new UdpClient(23450); var receiveTask = udpClient.ReceiveAsync(); var bufferPool = new ByteBufferPool(); var sock = new BareSock(bufferPool, AddressFamily.InterNetwork, new LoggerStub()); sock.Connect(IPAddress.Loopback, 23450); sock.Send(BitConverter.GetBytes(1), 0, 4, false); sock.Send(BitConverter.GetBytes(2), 0, 4, false); sock.Send(BitConverter.GetBytes(3), 0, 4, false); receiveTask.Wait(2000); Assert.AreEqual(TaskStatus.RanToCompletion, receiveTask.Status); Assert.LessOrEqual(1, BitConverter.ToInt32(receiveTask.Result.Buffer, 0)); receiveTask = udpClient.ReceiveAsync(); receiveTask.Wait(2000); Assert.AreEqual(TaskStatus.RanToCompletion, receiveTask.Status); Assert.LessOrEqual(2, BitConverter.ToInt32(receiveTask.Result.Buffer, 0)); // This test is flaky... receiveTask = udpClient.ReceiveAsync(); receiveTask.Wait(2000); Assert.AreEqual(TaskStatus.RanToCompletion, receiveTask.Status); Assert.AreEqual(3, BitConverter.ToInt32(receiveTask.Result.Buffer, 0)); sock.Close(); }
private bool AnalysisLogonRecord(Packet packet) { int dataStruct = Marshal.SizeOf(typeof(CMD_GH_LogonRecord)); if (packet.DataSize < dataStruct) { com.QH.QPGame.GameUtils.Logger.Net.LogError("LogonRecord Success Data Error CMD_GH_LogonRecord!"); return(false); } ByteBuffer listDataBuff = ByteBufferPool.PopPacket(packet.Data); int dataSzie = Marshal.SizeOf(typeof(CMD_GH_LogonRecord)); int dataCount = packet.DataSize / dataSzie; List <LogonRecordItem> logonRecordList = new List <LogonRecordItem>(); for (int i = 0; i < dataCount; i++) { byte[] tempData = listDataBuff.PopByteArray(dataSzie); CMD_GH_LogonRecord logonRecord = GameConvert.ByteToStruct <CMD_GH_LogonRecord>(tempData); LogonRecordItem logonItem = new LogonRecordItem(); logonItem.dwLogonIP = logonRecord.dwLogonIP; logonItem.dwTmlogonTime = logonRecord.dwTmlogonTime; logonRecordList.Add(logonItem); } ByteBufferPool.DropPacket(listDataBuff); GameApp.Account.CallLogonRecordEvent(logonRecordList); return(true); }
public byte[] ToBytes(Packet packet) { var pHead = new CMD_Head_8(); pHead.MainCmdID = (ushort)packet.MainCmd; pHead.SubCmdID = (ushort)packet.SubCmd; pHead.CheckCode = (byte)packet.CheckCode; pHead.DataSize = (ushort)(CommonDefine.TCP_HEAD_8_SIZE + packet.DataSize); pHead.MessageVer = (byte)CommonDefine.VERSION; var buffer = ByteBufferPool.PopPacket(); byte[] headBuffer = GameConvert.StructToByteArray <CMD_Head_8>(pHead); buffer.Position = 0; buffer.PushByteArray(headBuffer); if (packet.Data != null) { buffer.PushByteArray(packet.Data); } var bytes = buffer.ToByteArray(); ByteBufferPool.DropPacket(buffer); if (EnableEncrypt) { bytes = Encrypt(bytes); } return(bytes); }
public void Setup() { _cbs = new MockSmartCallbacks(); _bareSock = new MockSock(); _bufferPool = new ByteBufferPool(); _sock = new SmartSock(_bufferPool, _bareSock, _cbs); _remoteEndPoint = new IPEndPoint(IPAddress.Loopback, 23452); }
public void IncreaseBuffer() { var bufferPool = new ByteBufferPool(65536, 1); var buffer = bufferPool.Pop(); Assert.NotNull(buffer); Assert.Equal(65536, buffer.Length); }
static void ByteBufferPoolTest() { for (int i = 0; i < ByteBufferPool.sPool.Length; ++i) { var p = ByteBufferPool.sPool[i]; Debug.Assert(p.Count == ByteBufferPool.initialArraySize); for (int j = 0; j < p.Count; ++j) { Debug.Assert(p[j].Data.Length == 1 << (i + ByteBufferPool.minSizePOT)); } } int min = 1 << ByteBufferPool.minSizePOT; List <ByteBuffer> buffers = new List <ByteBuffer>(); buffers.Add(ByteBufferPool.Alloc(0)); buffers.Add(ByteBufferPool.Alloc(1)); buffers.Add(ByteBufferPool.Alloc(min - 1)); buffers.Add(ByteBufferPool.Alloc(min)); buffers.Add(ByteBufferPool.Alloc(min + 1)); var pool_64 = ByteBufferPool.sPool[ByteBufferPool.sIndexLookup[1 << ByteBufferPool.minSizePOT]]; Debug.Assert(ByteBufferPool.AvailableSlots(pool_64) == 0); var pool_128 = ByteBufferPool.sPool[ByteBufferPool.sIndexLookup[1 << (ByteBufferPool.minSizePOT + 1)]]; Debug.Assert(ByteBufferPool.AvailableSlots(pool_128) == ByteBufferPool.initialArraySize - 1); buffers.Add(ByteBufferPool.Alloc(min)); Debug.Assert(ByteBufferPool.AvailableSlots(pool_64) == ByteBufferPool.initialArraySize - 1); for (int i = 0; i < buffers.Count; ++i) { ByteBuffer bb = buffers[i]; ByteBufferPool.Dealloc(ref bb); Debug.Assert(null == bb); } Debug.Assert(ByteBufferPool.AvailableSlots(pool_64) == ByteBufferPool.initialArraySize * 2); Debug.Assert(ByteBufferPool.AvailableSlots(pool_128) == ByteBufferPool.initialArraySize); try { ByteBufferPool.Alloc((1 << ByteBufferPool.maxSizePOT) + 1); Debug.Assert(false); } catch (ArgumentOutOfRangeException) { } ByteBuffer wrongsize = new ByteBuffer(new byte[123]); ByteBufferPool.Dealloc(ref wrongsize); Debug.Assert(null != wrongsize); ByteBuffer exceed = new ByteBuffer(new byte[1 << ByteBufferPool.minSizePOT]); ByteBufferPool.Dealloc(ref exceed); Debug.Assert(null != exceed); Console.WriteLine("ByteBuffer Pool Checked"); }
public OutboundTest(ITestOutputHelper output) { var converter = new Converter(output); Console.SetOut(converter); _pool = new ByteBufferPool(10, 1024); _channelProvider = new MockManagedOutboundChannelProvider(Id.Of(1), Config); _outbound = new Outbound(_channelProvider, new ByteBufferPool(10, 10_000)); }
private void OnQueryIndividualResp(Packet packet) { ByteBuffer buffer = ByteBufferPool.PopPacket(packet.Data); //不需要只包含用户信息的数据包 buffer.Position = Marshal.SizeOf(typeof(CMD_GP_UserIndividual)); var info = new CMD_GH_UserInformation(); info.dwLogoID = GameApp.GameData.UserInfo.HeadId; while (true) { string str = ""; ushort type = ProtoHelper.ReadDescDataString(ref buffer, ref str); if (type == 0) { break; } switch (type) { case CommonDefine.DTP_GP_UI_COMPELLATION: { info.dwName = str; break; } case CommonDefine.DTP_GP_UI_QQ: { info.dwIM = str; break; } case CommonDefine.DTP_GP_UI_USER_NOTE: { info.dwIdentification = str; break; } case CommonDefine.DTP_GP_UI_MOBILE_PHONE: { info.dwCellPhone = str; break; } } } ByteBufferPool.DropPacket(buffer); GameApp.Account.CallUserInformationEvent( info.dwName, info.dwIdentification, info.dwCellPhone, info.dwIM, info.dwLogoID); }
public Cache() { _assetCache = new LRUCache <UUID, CacheEntry>(Config.Settings.Instance.CFCacheSize, true); _assetCache.OnItemPurged += _assetCache_OnItemPurged; int bufferPoolSize = (int)(Config.Settings.Instance.CFCacheSize * CACHE_VS_BUFFERPOOL_EXTENSION_FACTOR); _bufferPool = new ByteBufferPool(bufferPoolSize, BUFFER_SIZES); }
static void Main(string[] args) { var callbacks = new PrintingReceiver(); var bufferPool = new ByteBufferPool(); var sock = new SmartSock(bufferPool, new BareSock(bufferPool, AddressFamily.InterNetwork, new LoggerStub()), callbacks); var address = args[0]; callbacks.Connecting = true; Connect(address, sock); var packet = new ReceivedSmartPacket(); while (sock.State == PixocketState.Connecting) { if (sock.Receive(ref packet)) { break; } sock.Tick(); } for (int i = 1; i < 11; i++) { Thread.Sleep(1000); var buffer = CreateMessage(i); sock.Send(buffer, 0, buffer.Length, false); sock.Tick(); while (true) { if (sock.Receive(ref packet)) { callbacks.OnReceive(packet.Buffer, packet.Offset, packet.Length, packet.EndPoint, packet.InOrder); } else { break; } } if (!callbacks.Connected && !callbacks.Connecting) { callbacks.Connecting = true; Connect(address, sock); continue; } } sock.Disconnect(); while (sock.State == PixocketState.Connected) { sock.Tick(); sock.Receive(ref packet); Thread.Sleep(100); } }
public void TestPooledByteBuffer() { var testText = "Hello, PooledByteBuffer"; var pool = new ByteBufferPool(10, 100); var buffer1 = pool.Access(); buffer1.AsStream().Write(Converters.TextToBytes(testText)); Assert.Equal(testText, Converters.BytesToText(buffer1.Flip().ToArray())); }
public static IApplicationOutboundStream Instance( Stage stage, IManagedOutboundChannelProvider provider, ByteBufferPool byteBufferPool) { var definition = Definition.Has <ApplicationOutboundStreamActor>( Definition.Parameters(provider, byteBufferPool), "application-outbound-stream"); var applicationOutboundStream = stage.ActorFor <IApplicationOutboundStream>(definition); return(applicationOutboundStream); }
public void TestServiceLargeBytes() { var buffer = new ByteBufferPool(10, new int[] { 10, 20, 30 }); Assert.AreEqual(0, buffer.AllocatedBytes); var bytes = buffer.LeaseBytes(400); Assert.AreEqual(400, bytes.Length); buffer.ReturnBytes(bytes); Assert.AreEqual(0, buffer.AllocatedBytes); }
public void TestInvalidByteReturnSize() { var buffer = new ByteBufferPool(10, new int[] { 10, 20, 30 }); Assert.AreEqual(0, buffer.AllocatedBytes); buffer.ReturnBytes(new byte[40]); Assert.AreEqual(0, buffer.AllocatedBytes); buffer.ReturnBytes(new byte[5]); Assert.AreEqual(0, buffer.AllocatedBytes); }
public ApplicationOutboundStreamTest(ITestOutputHelper output) : base(output) { _world = TestWorld.Start("test-outbound-stream"); _localNodeId = Id.Of(1); _channelProvider = new MockManagedOutboundChannelProvider(_localNodeId, Config); _pool = new ByteBufferPool(10, Properties.OperationalBufferSize()); _outboundStream = _world.ActorFor <IApplicationOutboundStream>( Definition.Has <ApplicationOutboundStreamActor>( Definition.Parameters(_channelProvider, _pool))); }
private void AnalysisVersionInfo(Packet packet) { ByteBuffer buffer = ByteBufferPool.PopPacket(packet.Data); //不需要只包含用户信息的数据包 byte[] descData = buffer.PopByteArray(Marshal.SizeOf(typeof(CMD_GP_ClientUpdate))); CMD_GP_ClientUpdate version = GameConvert.ByteToStruct <CMD_GP_ClientUpdate>(descData); while (true) { string str = ""; ushort type = ProtoHelper.ReadDescDataString(ref buffer, ref str); if (type == 0) { break; } switch (type) { case CommonDefine.DTP_GP_CDN: { GameApp.GameData.CDN = str; break; } case CommonDefine.DTP_GP_OFFICESITE_URL: { GameApp.GameData.OfficeSiteUrl = str; break; } case CommonDefine.DTP_GP_BACK_STORGE_URL: { GameApp.GameData.BackStorgeUrl = str; break; } case CommonDefine.DTP_GP_MODULE_INFO: { GameApp.ModuleMgr.ApplyDataFromStr(str); break; } } } ByteBufferPool.DropPacket(buffer); GameApp.Account.CallVersionInfoEvent(version.dwVersion); }
public void FullUpdate(Msg_SC_Snapshot snapshot) { mServerTick = snapshot.TickNow; mSimulateTicks = 0; mTickObjects.FullUpdate(new TickObjectDictionary.TickObjectEnumerator(snapshot)); mHasFullUpdated = true; if (null != mProcessing) { ByteBufferPool.Dealloc(ref mProcessing); } while (mCachedSnapshots.Count > 0) { ByteBuffer bb = mCachedSnapshots.Dequeue(); ByteBufferPool.Dealloc(ref bb); } }
public static IOperationalOutboundStream Instance( Stage stage, Node node, IManagedOutboundChannelProvider provider, ByteBufferPool byteBufferPool) { var definition = Definition.Has <OperationalOutboundStreamActor>( Definition.Parameters(node, provider, byteBufferPool), "cluster-operational-outbound-stream"); var operationalOutboundStream = stage.ActorFor <IOperationalOutboundStream>(definition); return(operationalOutboundStream); }
void Simulate() { if (null == mProcessing && mCachedSnapshots.Count < cacheSnapshots) { return; } if (null == mProcessing) { mProcessing = mCachedSnapshots.Dequeue(); } int simulateCount = 1; uint sot = Game.Instance.snapshotOverTick; if (mCachedSnapshots.Count > cacheSnapshots - 1) { uint k = (uint)mCachedSnapshots.Count; uint ticksToSimulate = (k + 1) * sot - mSimulateTicks; uint ticksSupposeToSimulate = cacheSnapshots * sot - mSimulateTicks; simulateCount = Mathf.Max(1, Mathf.FloorToInt((float)ticksToSimulate / ticksSupposeToSimulate)); } Msg_SC_Snapshot ss = InstancePool.Get <Msg_SC_Snapshot>(); Msg_SC_Snapshot.GetRootAsMsg_SC_Snapshot(mProcessing, ss); for (int i = 0; i < simulateCount; ++i) { mServerTick = ss.TickNow - sot + mSimulateTicks; float nt = (float)(mSimulateTicks + 1) / sot; mTickObjects.Simulate(nt, new TickObjectDictionary.TickObjectEnumerator(ss)); ++mSimulateTicks; ++mServerTick; if (mSimulateTicks >= sot) { mSimulateTicks = 0; ByteBufferPool.Dealloc(ref mProcessing); if (mCachedSnapshots.Count <= 0) { break; } mProcessing = mCachedSnapshots.Dequeue(); Msg_SC_Snapshot.GetRootAsMsg_SC_Snapshot(mProcessing, ss); } } }
static void Main(string[] args) { var callbacks = new ReplServ(); var bufferPool = new ByteBufferPool(); var sock = new SmartSock(bufferPool, new BareSock(bufferPool, AddressFamily.InterNetwork, new LoggerStub()), callbacks); callbacks.SetSocket(sock); sock.Listen(2345); while (true) { Thread.Sleep(100); callbacks.Tick(); } }
/// <exception cref="System.IO.IOException"/> /// <exception cref="System.NotSupportedException"/> public virtual ByteBuffer Read(ByteBufferPool bufferPool, int maxLength, EnumSet< ReadOption> opts) { try { return ((HasEnhancedByteBufferAccess)@in).Read(bufferPool, maxLength, opts); } catch (InvalidCastException) { ByteBuffer buffer = ByteBufferUtil.FallbackRead(this, bufferPool, maxLength); if (buffer != null) { extendedReadBuffers.Put(buffer, bufferPool); } return buffer; } }
public virtual void ReleaseBuffer(ByteBuffer buffer) { try { ((HasEnhancedByteBufferAccess)@in).ReleaseBuffer(buffer); } catch (InvalidCastException) { ByteBufferPool bufferPool = extendedReadBuffers.Remove(buffer); if (bufferPool == null) { throw new ArgumentException("tried to release a buffer " + "that was not created by this stream." ); } bufferPool.PutBuffer(buffer); } }
/// <summary> /// Constructs a new asset cache /// </summary> /// <param name="maxEntryAge">The maximum age for a cache entry before it becomes a candidate to be purged</param> public Cache(int maxEntryAge = 0) { _assetCache = new LRUCache<UUID, CacheEntry>(Config.Settings.Instance.CFCacheSize, true, (int)(Config.Settings.Instance.CFCacheSize * 0.1f), maxEntryAge); _assetCache.OnItemPurged += _assetCache_OnItemPurged; int bufferPoolSize = (int)(Config.Settings.Instance.CFCacheSize * CACHE_VS_BUFFERPOOL_EXTENSION_FACTOR); _bufferPool = new ByteBufferPool(bufferPoolSize, BUFFER_SIZES, (ulong)maxEntryAge); }