using CommonLang.Log; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CommonServer.SSocket.SuperSocket { public class EmulateLagging { private Logger log = LoggerFactory.GetLogger("EmulateLagging"); private Thread mEmuLagThread; private bool running = true; private int mLagMinTimeMS; private int mLagMaxTimeMS; private Queue emu_lag_queue = new Queue(); private Random random = new Random(); public bool EmulateLag { get { return mLagMinTimeMS > 0; } } public EmulateLagging() { this.mEmuLagThread = new Thread(loop); } public void SetEmulateLaggingMS(int min, int max) { this.mLagMinTimeMS = Math.Min(min, max); this.mLagMaxTimeMS = Math.Max(min, max); } public void GetEmulateLaggingMS(out int min, out int max) { min = this.mLagMinTimeMS; max = this.mLagMaxTimeMS; } public void Start() { this.running = true; this.mEmuLagThread.Start(); } public void Pause() { } public void Resume() { } public void Dispose() { this.running = false; if (mEmuLagThread.IsAlive) { lock (emu_lag_queue) { Monitor.Pulse(emu_lag_queue); } this.mEmuLagThread.Join(); } } public void SendDelay(Session session, byte[] buff, int offset, int length) { lock (emu_lag_queue) { emu_lag_queue.Enqueue(new EmuPack(session, buff, offset, length)); Monitor.Pulse(emu_lag_queue); } } private void loop() { while (running) { try { lock (emu_lag_queue) { Monitor.Wait(emu_lag_queue); while (emu_lag_queue.Count > 0) { EmuPack pak = emu_lag_queue.Dequeue(); pak.session.Send(pak.buff, pak.offset, pak.length); } } Thread.Sleep(random.Next(mLagMinTimeMS, mLagMaxTimeMS)); } catch(Exception err) { log.Error(err.Message, err); } } } private struct EmuPack { public Session session; public byte[] buff; public int offset; public int length; public EmuPack(Session session, byte[] buff, int offset, int length) { this.session = session; this.buff = buff; this.offset = offset; this.length = length; } } } }