|
المشاركات 1,940 |
+التقييم 0.95 |
تاريخ التسجيل Apr 2019 |
الاقامة Egypt |
نظام التشغيل windows 7 |
رقم العضوية 1 |
using System;
using Project_Terror_v2.Game.MsgServer;
using Project_Terror_v2.Game.MsgFloorItem;
namespace Project_Terror_v2.Game.MsgMonster
{
public class PoolProcesses
{
public unsafe static void BuffersCallback(Client.GameClient client, Extensions.Time32 clock)
{
try
{
Extensions.Time32 timer = Extensions.Time32.Now;
var Array = client.Player.View.Roles(Role.MapObjectType.Monster);
foreach (var map_mob in Array)
{
var Mob = (map_mob as MonsterRole);
if (Mob.IsFloor)
{
if (Mob.FloorPacket.m_ID == Game.MsgFloorItem.MsgItemPacket.Thundercloud && DateTime.Now > Mob.FloorStampTimer)
{
Mob.FloorStampTimer = DateTime.Now.AddSeconds(1);
Mob.StampFloorSecounds -= 1000;
if(DateTime.Now > Mob.RemoveFloor)
{
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
ActionQuery action;
action = new ActionQuery()
{
ObjId = Mob.FloorPacket.m_UID,
Type = ActionType.RemoveEntity
};
Mob.View.SendScreen(stream.ActionCreate(&action), Mob.GMap);
Mob.GMap.View.LeaveMap<Role.IMapObj>(Mob);
Mob.HitPoints = 0;
client.Map.SetMonsterOnTile(Mob.X, Mob.Y, false);
}
}
}
else if (Mob.FloorPacket.m_ID == Game.MsgFloorItem.MsgItemPacket.AuroraLotus && DateTime.Now > Mob.FloorStampTimer)
{
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
Mob.FloorPacket.DropType = MsgFloorItem.MsgDropID.RemoveEffect;
foreach (var user in Mob.View.Roles(client.Map, Role.MapObjectType.Player))
{
if (user.Alive == false)
{
if (Role.Core.GetDistance(user.X, user.Y, Mob.X, Mob.Y) < 5)
{
var player = user as Role.Player;
if (player.ContainFlag(MsgUpdate.Flags.SoulShackle) == false)
player.Revive(stream);
}
}
// user.Send(Mob.GetArray(stream, false));
}
ActionQuery action;
action = new ActionQuery()
{
ObjId = Mob.FloorPacket.m_UID,
Type = ActionType.RemoveEntity
};
Mob.View.SendScreen(stream.ActionCreate(&action), Mob.GMap);
Mob.GMap.View.LeaveMap<Role.IMapObj>(Mob);
Mob.HitPoints = 0;
client.Map.SetMonsterOnTile(Mob.X, Mob.Y, false);
}
}
else if (Mob.FloorPacket.m_ID == Game.MsgFloorItem.MsgItemPacket.FlameLotus && DateTime.Now > Mob.FloorStampTimer)
{
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
Mob.FloorPacket.DropType = MsgFloorItem.MsgDropID.RemoveEffect;
uint experience = 0;
foreach (var user in Mob.View.Roles(client.Map, Role.MapObjectType.Player))
{
if (user.UID != Mob.OwnerFloor.Player.UID && Role.Core.GetDistance(user.X, user.Y, Mob.X, Mob.Y) < 5)
{
var player = user as Role.Player;
if (MsgServer.AttackHandler.CheckAttack.CanAttackPlayer.Verified(Mob.OwnerFloor, player, null))
{
Game.MsgServer.MsgSpellAnimation.SpellObj AnimationObj;
Game.MsgServer.AttackHandler.Calculate.Magic.OnPlayer(Mob.OwnerFloor.Player, player, Mob.DBSpell, out AnimationObj);
Game.MsgServer.AttackHandler.ReceiveAttack.Player.Execute(AnimationObj, Mob.OwnerFloor, player);
AnimationObj.Damage = Game.MsgServer.AttackHandler.Calculate.Base.CalculateSoul(AnimationObj.Damage, 0);
InteractQuery Attack = new InteractQuery();
Attack.UID = Mob.UID;
Attack.OpponentUID = player.UID;
Attack.Damage = (int)AnimationObj.Damage;
Attack.Effect = AnimationObj.Effect;
Attack.X = player.X;
Attack.Y = player.Y;
Attack.AtkType = MsgAttackPacket.AttackID.Physical;
stream.InteractionCreate(&Attack);
player.View.SendView(stream, true);
}
}
user.Send(Mob.GetArray(stream, false));
}
foreach (var obj in Mob.OwnerFloor.Player.View.Roles(Role.MapObjectType.Monster))
{
if (Role.Core.GetDistance(obj.X, obj.Y, Mob.X, Mob.Y) < 5)
{
var monster = obj as Game.MsgMonster.MonsterRole;
if (monster.UID != Mob.UID)
{
Game.MsgServer.MsgSpellAnimation.SpellObj AnimationObj;
Game.MsgServer.AttackHandler.Calculate.Magic.OnMonster(Mob.OwnerFloor.Player, monster, Mob.DBSpell, out AnimationObj);
Game.MsgServer.AttackHandler.ReceiveAttack.Monster.Execute(stream, AnimationObj, Mob.OwnerFloor, monster);
AnimationObj.Damage = Game.MsgServer.AttackHandler.Calculate.Base.CalculateSoul(AnimationObj.Damage, 0);
experience += AnimationObj.Damage;
InteractQuery Attack = new InteractQuery();
Attack.UID = Mob.UID;
Attack.OpponentUID = Mob.UID;
Attack.Damage = (int)AnimationObj.Damage;
Attack.Effect = AnimationObj.Effect;
Attack.X = Mob.X;
Attack.Y = Mob.Y;
Attack.AtkType = MsgAttackPacket.AttackID.Physical;
stream.InteractionCreate(&Attack);
monster.View.SendScreen(stream, client.Map);
}
}
}
var DBSpells = Database.Server.Magic[(ushort)Role.Flags.SpellID.FlameLotus];
MsgServer.AttackHandler.Updates.IncreaseExperience.Up(stream, Mob.OwnerFloor, experience);
MsgServer.AttackHandler.Updates.UpdateSpell.CheckUpdate(stream, Mob.OwnerFloor, new InteractQuery()
{
SpellID = (ushort)Role.Flags.SpellID.FlameLotus
}, experience, DBSpells);
Mob.FloorPacket.DropType = MsgFloorItem.MsgDropID.Remove;
Mob.View.SendScreen(stream.ItemPacketCreate(Mob.FloorPacket), Mob.GMap);
ActionQuery action;
action = new ActionQuery()
{
ObjId = Mob.FloorPacket.m_UID,
Type = ActionType.RemoveEntity
};
unsafe
{
Mob.View.SendScreen(stream.ActionCreate(&action), Mob.GMap);
}
// Mob.FloorPacket.DropType = MsgFloorItem.MsgDropID.RemoveEffect;
// Mob.View.SendScreen(stream.ItemPacketCreate(Mob.FloorPacket), Mob.GMap);
Mob.GMap.View.LeaveMap<Role.IMapObj>(Mob);
Mob.HitPoints = 0;
//client.Map.MonstersColletion.Roles.Remove(Mob.UID);
client.Map.SetMonsterOnTile(Mob.X, Mob.Y, false);
}
}
continue;
}
if (Mob.BlackSpot)
{
if (timer > Mob.Stamp_BlackSpot)
{
Mob.BlackSpot = false;
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
Mob.Send(stream.BlackspotCreate(false, Mob.UID));
}
}
}
foreach (var flag in Mob.BitVector.GetFlags())
{
if (flag.Expire(timer))
{
Mob.RemoveFlag((MsgServer.MsgUpdate.Flags)flag.Key, client.Map);
}
else if (flag.Key == (int)Game.MsgServer.MsgUpdate.Flags.ScarofEarth)
{
if (flag.CheckInvoke(timer))
{
if (Mob.ScarofEarthl != null && Mob.AttackerScarofEarthl != null)
{
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
var DBSpell = Mob.ScarofEarthl;
MsgSpellAnimation MsgSpell = new MsgSpellAnimation( Mob.UID, 0, Mob.X, Mob.Y, DBSpell.ID, DBSpell.Level, 0, 1);
MsgSpellAnimation.SpellObj AnimationObj = new MsgSpellAnimation.SpellObj()
{
UID = Mob.UID,
Damage = (uint)DBSpell.Damage2,
Hit = 1
};
Game.MsgServer.AttackHandler.ReceiveAttack.Monster.Execute(stream, AnimationObj, Mob.AttackerScarofEarthl, Mob);
MsgSpell.SetStream(stream);
MsgSpell.Targets.Enqueue(AnimationObj);
MsgSpell.Send(client);
}
}
}
}
else if (flag.Key == (int)Game.MsgServer.MsgUpdate.Flags.Poisoned)
{
if (flag.CheckInvoke(timer))
{
uint damage = Game.MsgServer.AttackHandler.Calculate.Base.CalculatePoisonDamage(Mob.HitPoints, Mob.PoisonLevel);
if (Mob.HitPoints == 1)
{
damage = 0;
goto jump;
}
Mob.HitPoints = (uint)Math.Max(1, (int)(Mob.HitPoints - damage));
jump:
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
InteractQuery action = new InteractQuery()
{
Damage = (int)damage,
AtkType = MsgAttackPacket.AttackID.Physical,
X = Mob.X,
Y = Mob.Y,
OpponentUID = Mob.UID
};
Mob.Send(stream.InteractionCreate(&action));
}
}
}
}
}
}
catch (Exception e)
{
MyConsole.WriteException(e);
}
}
public static void GuardsCallback(Client.GameClient client, Extensions.Time32 clock)
{
try
{
if (client.Map == null)
return;
Extensions.Time32 timer = Extensions.Time32.Now;
var Array = client.Player.View.Roles(Role.MapObjectType.Monster);
foreach (var map_mob in Array)
{
var Guard = (map_mob as MonsterRole);
if ((Guard.Family.Settings & MonsterSettings.Guard) == MonsterSettings.Guard)
{
if (timer > Guard.AttackSpeed.AddMilliseconds(Guard.Family.AttackSpeed))
{
client.Player.View.MobActions.CheckGuardPosition(client.Player.View.GetPlayer(), Guard);
if (client.Player.View.MobActions.GuardAttackPlayer(client.Player.View.GetPlayer(), Guard))
Guard.AttackSpeed = timer;
if (!Guard.Alive)
{
Guard.AddFadeAway(timer.AllMilliseconds, client.Map);
Guard.RemoveView(timer.AllMilliseconds, client.Map);
}
foreach (var mob in Array)
{
var monseter = (mob as MonsterRole);
if ((monseter.Family.Settings & MonsterSettings.Guard) != MonsterSettings.Guard
&& (monseter.Family.Settings & MonsterSettings.Reviver) != MonsterSettings.Reviver
&& !monseter.IsFloor)
{
if (client.Player.View.MobActions.GuardAttackMonster(client.Map, monseter, Guard))
break;
}
}
}
}
}
}
catch (Exception e)
{
MyConsole.WriteException(e);
}
}
public static void AliveMonstersCallback(Client.GameClient client, Extensions.Time32 clock)
{
try
{
if (client.Map == null)
return;
Extensions.Time32 timer = Extensions.Time32.Now;
var Array = client.Player.View.Roles(Role.MapObjectType.Monster);
foreach (var map_mob in Array)
{
var monster = (map_mob as MonsterRole);
if (!map_mob.Alive)
{
if (monster.State == Game.MsgMonster.MobStatus.Respawning)
{
if (MonsterRole.SpecialMonsters.Contains(monster.Family.ID))
continue;
if (timer > monster.RespawnStamp)
{
if (!client.Map.MonsterOnTile(monster.RespawnX, monster.RespawnY))
{
monster.Respawn();
client.Map.SetMonsterOnTile(monster.X, monster.Y, true);
}
}
}
}
if ((monster.Family.Settings & MonsterSettings.Guard) != MonsterSettings.Guard
&& (monster.Family.Settings & MonsterSettings.Reviver) != MonsterSettings.Reviver
&& (monster.Family.Settings & MonsterSettings.Lottus) != MonsterSettings.Lottus)
{
var Mob = map_mob as MonsterRole;
if (Mob.Family.ID == 20211)
continue;
client.Player.View.MobActions.ExecuteAction(client.Player.View.GetPlayer(), Mob);
if (!Mob.Alive)
{
var now = Extensions.Time32.Now;
Mob.AddFadeAway(now.AllMilliseconds, client.Map);
Mob.RemoveView(now.AllMilliseconds, client.Map);
}
}
}
}
catch (Exception e)
{
MyConsole.WriteException(e);
}
}
private unsafe static void ReviversCallback(Client.GameClient client)
{
try
{
if (client.Map == null)
return;
var Array = client.Player.View.Roles(Role.MapObjectType.Monster);
foreach (var map_mob in Array)
{
var monseter = (map_mob as MonsterRole);
if ((monseter.Family.Settings & MonsterSettings.Reviver) == MonsterSettings.Reviver)
{
if (!monseter.Alive)
{
var now = Extensions.Time32.Now.AllMilliseconds;
monseter.AddFadeAway(now, client.Map);
monseter.RemoveView(now, client.Map);
}
if (Role.Core.GetDistance(map_mob.X, map_mob.Y, client.Player.View.GetPlayer().X, client.Player.View.GetPlayer().Y) < 13)
{
if (!client.Player.View.GetPlayer().Alive)
{
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
client.Player.View.GetPlayer().Revive(stream);
}
using (var rec = new ServerSockets.RecycledPacket())
{
var stream = rec.GetStream();
MsgServer.MsgSpellAnimation SpellPacket = new MsgServer.MsgSpellAnimation(map_mob.UID
, 0, map_mob.X, map_mob.Y, (ushort)Role.Flags.SpellID.Pray, 0, 0);
SpellPacket.Targets.Enqueue(new MsgServer.MsgSpellAnimation.SpellObj(client.Player.View.GetPlayer().UID, 0, MsgServer.MsgAttackPacket.AttackEffect.None));
SpellPacket.SetStream(stream);
SpellPacket.Send(map_mob as Game.MsgMonster.MonsterRole);
}
}
}
}
}
}
catch (Exception e)
{
MyConsole.WriteException(e);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Project_Terror_v2.ServerSockets
{
public class BruteForceEntry
{
public string IPAddress;
public int WatchCheck;
public Extensions.Time32 Unbantime;
public Extensions.Time32 AddedTimeRemove;
}
public class BruteforceProtection
{
private Extensions.SafeDictionary<string, BruteForceEntry> collection = new Extensions.SafeDictionary<string, BruteForceEntry>();
private int BanOnWatch;
private void _internalInit()
{
Extensions.Time32 Now;
while (true)
{
Now = Extensions.Time32.Now;
foreach (BruteForceEntry bfe in collection.GetValues())
{
if (bfe.AddedTimeRemove <= Now)
{
collection.Remove(bfe.IPAddress);
}
else if (bfe.Unbantime.Value != 0)
{
if (bfe.Unbantime.Value <= Now.Value)
{
collection.Remove(bfe.IPAddress);
}
}
}
Thread.Sleep(2000);
}
}
public void Init(int WatchBeforeBan)
{
BanOnWatch = WatchBeforeBan;
new Thread(new ThreadStart(_internalInit)).Start();
}
public void AddWatch(string IPAddress)
{
lock (collection)
{
BruteForceEntry bfe;
if (!collection.TryGetValue(IPAddress, out bfe))
{
bfe = new BruteForceEntry();
bfe.IPAddress = IPAddress;
bfe.WatchCheck = 1;
bfe.AddedTimeRemove = Extensions.Time32.Now.AddMinutes(3);
bfe.Unbantime = new Extensions.Time32(0);
collection.Add(IPAddress, bfe);
}
else
{
bfe.WatchCheck++;
if (bfe.WatchCheck >= BanOnWatch)
{
Console.WriteLine(IPAddress + "Has been ban");
bfe.Unbantime = Extensions.Time32.Now.AddMinutes(3);
}
}
}
}
public bool AllowAddress(string IPAddress)
{
foreach (var server in Database.GroupServerList.GroupServers.Values)
if (server.IPAddress == IPAddress)
return false;
return false;
}
public bool IsBanned(string IPAddress)
{
bool check = false;
BruteForceEntry bfe;
if (collection.TryGetValue(IPAddress, out bfe))
{
check = (bfe.Unbantime.Value != 0);
}
return check;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_Terror_v2.ServerSockets
{
public class ConcurrentPacketQueue
{
const int capacity = 8191;
private byte[] queue = new byte[capacity + 1];
private int enqueuePointer = 0, dequeuePointer = 0, enqueuedData = 0,
currentPacketSize = -1, tqPadding;
private object syncRoot;
public ConcurrentPacketQueue(int padding = 8)
{
tqPadding = padding;
syncRoot = new object();
}
public int CurrentLength { get { reviewPacketSize(); return currentPacketSize; } }
public unsafe void Enqueue(byte[] buffer, int length)
{
lock (syncRoot)
{
for (int i = 0; i < length; i++, enqueuePointer++)
queue[enqueuePointer & capacity] = buffer[i];
enqueuedData += length;
}
}
private void reviewPacketSize()
{
lock (syncRoot)
{
if (enqueuedData < 2) currentPacketSize = -1;
else currentPacketSize = ((queue[dequeuePointer & capacity] | (queue[(dequeuePointer + 1) & capacity] << 8)) + tqPadding);
}
}
public bool CanDequeue()
{
reviewPacketSize();
if (currentPacketSize == -1) return false;
return (enqueuedData >= currentPacketSize);
}
public byte[] Dequeue()
{
lock (syncRoot)
{
if (currentPacketSize == -1 || enqueuedData < currentPacketSize)
throw new OperationCanceledException("Before calling Dequeue(), always call CanDequeue()!");
byte[] array = new byte[currentPacketSize];
for (int i = 0; i < currentPacketSize; i++, dequeuePointer++)
array[i] = queue[dequeuePointer & capacity];
enqueuedData -= currentPacketSize;
reviewPacketSize();
return array;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_Terror_v2.ServerSockets
{
public class LoginController
{
private static Dictionary<string, byte> LoginControllerContainer = new Dictionary<string, byte>();
public static bool CanLogin(string IP)
{
byte logintimes = 0;
if (LoginControllerContainer.TryGetValue(IP, out logintimes))
{
return logintimes < 3;
}
else
{
LoginControllerContainer.Add(IP, 0);
return true;
}
}
public static void LoggedIn(string IP)
{
try
{
if (LoginControllerContainer.ContainsKey(IP))
{
byte times = LoginControllerContainer[IP];
LoginControllerContainer.Remove(IP);
times += 1;
LoginControllerContainer.Add(IP, times);
}
}
catch { }
}
public static void Disconnect(string IP)
{
try
{
if (LoginControllerContainer.ContainsKey(IP))
{
byte times = LoginControllerContainer[IP];
LoginControllerContainer.Remove(IP);
if (times > 0)
{
times -= 1;
}
LoginControllerContainer.Add(IP, times);
}
}
catch { }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Project_Terror_v2.ServerSockets
{
public unsafe class Packet : IDisposable
{
public const int MAX_SIZE = 1024;
private const int TQ_SEALSIZE = 8;
private static string seal;
/*[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void* memcpy(void* dst, void* src, int num);*/
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern void* memset(void* dst, int val, int count);
public static string SealString
{
get { return seal; }
set
{
if (value.Length != TQ_SEALSIZE)
throw new ArgumentOutOfRangeException("value", "Packet seal must be " + TQ_SEALSIZE + " chars long.");
seal = value;
}
}
public static int SealSize
{
get { return seal != null ? TQ_SEALSIZE : 0; }
}
public int Size { get; set; }
public byte* Memory { get; private set; }
private bool IsDisposed = false;
public byte* stream;
public int Position { get { return (int)(stream - Memory); } }
// public byte* Pointer { get { return stream; } }
public Packet(byte[] buffer)
{
Memory = (byte*)Marshal.AllocHGlobal(1024);
stream = Memory;
Marshal.Copy(buffer, 0, (IntPtr)this.stream, buffer.Length);
this.Size = buffer.Length;
}
public Packet(int size)
{
Memory = (byte*)Marshal.AllocHGlobal(size);
stream = Memory;
}
~Packet()
{
this.Dispose();
}
public void Dispose()
{
// lock (this)
{
if (this.IsDisposed) return;
IsDisposed = true;
if ((IntPtr)this.Memory == IntPtr.Zero)
return;
Marshal.FreeHGlobal((IntPtr)this.Memory);
this.Memory = null;
GC.SuppressFinalize(this);
}
}
public void InitWriter()
{
Seek(4);
}
public void Seek(int offset)
{
stream = &Memory[offset];
}
public void SeekForward(int amount)
{
Seek(Position + amount);
}
public void SeekBackwards(int amount)
{
Seek(Position - amount);
}
public void Write(byte value)
{
if (Position + 1 >= MAX_SIZE)
return;
*stream = value;
stream++;
}
public void Write(ushort value)
{
if (Position + 2 >= MAX_SIZE)
return;
*((ushort*)stream) = value;
stream += sizeof(ushort);
}
public void Write(uint value)
{
if (Position + 4 >= MAX_SIZE)
return;
*((uint*)stream) = value;
stream += sizeof(uint);
}
public void Write(ulong value)
{
if (Position + 8 >= MAX_SIZE)
return;
*((ulong*)stream) = value;
stream += sizeof(ulong);
}
public void Write(sbyte value) { Write((byte)value); }
public void Write(short value) { Write((ushort)value); }
public void Write(int value) { Write((uint)value); }
public void Write(long value) { Write((ulong)value); }
public void Write(string value, int length)
{
int min = Math.Min(value.Length, length);
var buf = Encoding.Default.GetBytes(value);
for (int i = 0; i < min; i++)
Write(buf[i]);
ZeroFill(length - min);
}
public void Write(params string[] value)
{
Write((byte)value.Length);
for (int i = 0; i < value.Length; i++)
{
var str = value[i];
if (string.IsNullOrEmpty(str))
{
Write((byte)0);
continue;
}
Write((byte)str.Length);
Write(str, str.Length);
}
}
public void WriteUnsafe(void* buf, int length)
{
if (Position + length >= MAX_SIZE)
return;
memcpy(stream, buf, length);
stream += length;
}
public void ZeroFill(int amount)
{
if (Position + amount >= MAX_SIZE)
return;
memset(stream, 0, amount);
stream += amount;
}
public string[] ReadStringList()
{
var result = new string[ReadUInt8()];
for (int i = 0; i < result.Length; i++)
result[i] = ReadCString(ReadUInt8());
return result;
}
public void ReadUnsafe(void* buf, int length)
{
if (Position + length >= MAX_SIZE)
return;
memcpy(buf, stream, length);
stream += length;
}
public byte[] ReadBytes(int size)
{
byte[] res = new byte[size];
for (int i = 0; i < res.Length; i++)
res[i] = ReadUInt8();
return res;
}
public string ReadCString(int size)
{
if (Position + size >= MAX_SIZE)
return "";
string result = new string((sbyte*)this.stream, 0, size);
stream += size;
int idx = result.IndexOf('\0');
return (idx > -1) ? result.Substring(0, idx) : result;
}
public byte ReadUInt8()
{
if (Position + 1 >= MAX_SIZE)
return 0;
var result = *stream;
stream++;
return result;
}
public ushort ReadUInt16()
{
if (Position + 2 >= MAX_SIZE)
return 0;
var result = *((ushort*)stream);
stream += sizeof(ushort);
return result;
}
public uint ReadUInt32()
{
if (Position + 4 >= MAX_SIZE)
return 0;
var result = *((uint*)stream);
stream += sizeof(uint);
return result;
}
public ulong ReadUInt64()
{
if (Position + 8 >= MAX_SIZE)
return 0;
var result = *((ulong*)stream);
stream += sizeof(ulong);
return result;
}
public sbyte ReadInt8() { return (sbyte)ReadUInt8(); }
public short ReadInt16() { return (short)ReadUInt16(); }
public int ReadInt32() { return (int)ReadUInt32(); }
public long ReadInt64() { return (long)ReadUInt64(); }
public void Finalize(ushort type)
{
if (SealSize > 0)
{
WriteSeal();
}
this.Size = this.Position;
Seek(0);
Write((ushort)(this.Size - SealSize));
Write((ushort)type);
}
public void ProtoBufferSerialize(object obj)
{
using (var ms = new System.IO.MemoryStream())
{
ProtoBuf.Serializer.Serialize(ms, obj);
byte[] array = ms.ToArray();
fixed (byte* proto_ptr = array)
memcpy(stream, proto_ptr, array.Length);
stream += array.Length;
}
}
public T ProtoBufferDeserialize<T>(T obj)
{
Seek(0);
ushort packet_length = ReadUInt16();
ReadUInt16();
byte[] array = new byte[packet_length - 4];
array = ReadBytes(packet_length - 4);
using (var ms = new System.IO.MemoryStream(array))
{
obj = ProtoBuf.Serializer.Deserialize<T>(ms);
}
return obj;
}
public T ProtoBufferDeserialize<T>(T obj, byte[] packet)
{
using (var ms = new System.IO.MemoryStream(packet))
{
obj = ProtoBuf.Serializer.Deserialize<T>(ms);
}
return obj;
}
public void WriteSeal()
{
Write(SealString, TQ_SEALSIZE); // NOTE: must be 8 chars
}
private static string CreatePacketStringWithNumbers(byte* b, int len)
{
//
// -- Taken from ConquerAI
// Special Thanks: John
//
int msgSize = (len) * 4 //4 chars, 2 for number, 1 for white space, 1 for letter
+ ((len / 16) + 1) * 9; //1 for /t and 2 for new line/ret, 3 for number, 2 for [ ] and 1 for space
StringBuilder hex = new StringBuilder(msgSize);
for (int i = 0; i < len; i += 16)
{
hex.AppendFormat("[{0:000}] ", i);
for (int z = i; z < i + 16; z++)
{
if (z >= len) hex.Append(" ");
else
hex.AppendFormat("{0:x2} ", b[z]);
}
hex.Append('\t');
for (int z = i; z < i + 16; z++)
{
if (z >= len) hex.Append(" ");
else
{
if (b[z] > 32 && b[z] < 127)
{
hex.AppendFormat("{0}", (char)b[z]);
}
else
{
hex.Append('.');
}
}
}
hex.Append("\r\n");
}
return hex.ToString();
}
public static string Dump(byte[] b)
{
fixed (byte* ptr = b)
return CreatePacketStringWithNumbers(ptr, b.Length);
}
public string Dump(string header)
{
int offset = Position; Seek(2);
int type = ReadUInt16(); Seek(offset);
string str = "Packet (" + header + ") - Type: " + type + " Size - " + Size + "\r\n";
str += CreatePacketStringWithNumbers(this.Memory, this.Size);
return str;
}
public unsafe void memcpy(void* dest, void* src, Int32 size)
{
Int32 count = size / sizeof(long);
for (Int32 i = 0; i < count; i++)
*(((long*)dest) + i) = *(((long*)src) + i);
Int32 pos = size - (size % sizeof(long));
for (Int32 i = 0; i < size % sizeof(long); i++)
*(((Byte*)dest) + pos + i) = *(((Byte*)src) + pos + i);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
namespace Project_Terror_v2.ServerSockets
{
public class RecycledPacket : IDisposable
{
private Packet stream;
public Packet GetStream() { return stream; }
public RecycledPacket()
{
this.stream = PacketRecycle.Take();
}
~RecycledPacket()
{
this.Dispose();
}
public void Dispose()
{
if (stream == null)
return;
PacketRecycle.Reuse(stream);
stream = null;
GC.SuppressFinalize(this);
}
}
public static class PacketRecycle
{
public static int Count
{
get { return bin.Count; }
}
private static ConcurrentQueue<Packet> bin = new ConcurrentQueue<Packet>();
public static Packet Take()
{
Packet from;
if (!bin.TryDequeue(out from))
from = new Packet(Packet.MAX_SIZE);
from.Seek(4);
return from;
}
public static void Reuse(Packet old)
{
old.Seek(0);
bin.Enqueue(old);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_Terror_v2.ServerSockets
{
public class ReceiveBuffer
{
public const int RECV_BUFFER_SIZE = 4096;//16384;//8192;//2048;
public const int HeadSize = 1024;
public byte[] buffer;
private int nLen;
public ReceiveBuffer(int ReceiveBufferSize, bool changesize = false)
{
if (changesize)
{
buffer = new byte[ReceiveBufferSize];
}
else
{
// if (ReceiveBufferSize == 0)
buffer = new byte[RECV_BUFFER_SIZE];//RECV_BUFFER_SIZE];
//else
// buffer = new byte[ReceiveBufferSize];
}
Reset();
}
public void AddLength(int length)
{
nLen += length;
}
public ushort ReadHead()
{
return BitConverter.ToUInt16(buffer, 0);
}
public void DelLength(int length)
{
nLen -= length;
}
public int Length() { return nLen; }
public int MaxLength() { return buffer.Length; }
public void Reset()
{
nLen = 0;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Project_Terror_v2.ServerSockets
{
public unsafe class SecuritySocket
{
public ReceiveBuffer ReceiveBuff;
public bool IsGameServer
{
get
{
return Crypto != null;
}
}
public bool SetDHKey = false;
private Action<SecuritySocket> OnDisconnect;
private Action<SecuritySocket, Packet> OnReceiveHandler;
public Socket Connection;
public object Client;
private IDisposable[] TimerSubscriptions = null;
public bool Alive = false;
public Cryptography.TQCast5 Crypto;
public bool OnInterServer = false;
public string RemoteIp
{
get
{
try
{
if (Connection == null)
return "NONE";
return (Connection.RemoteEndPoint as IPEndPoint).Address.ToString();
}
catch
{
return "NONE";
}
}
}
public Extensions.Time32 LastReceive;
public Client.GameClient Game;
public ServerSocket Server;
public bool ConnectFull = false;
public SecuritySocket(ServerSocket serversocket, Action<SecuritySocket> _OnDisconnect, Action<SecuritySocket, Packet> _OnReceiveHandler)
{
Server = serversocket;
OnReceiveHandler = _OnReceiveHandler;
OnDisconnect = _OnDisconnect;
}
public SecuritySocket(Action<SecuritySocket> _OnDisconnect, Action<SecuritySocket, Packet> _OnReceiveHandler)
{
OnReceiveHandler = _OnReceiveHandler;
OnDisconnect = _OnDisconnect;
}
public bool Connect(string IPAddres, ushort port, out Socket _socket)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult asyncResult = _socket.BeginConnect(new IPEndPoint(IPAddress.Parse(IPAddres), port), null, null);
uint count = 0;
while (!asyncResult.IsCompleted && count < 10)
{
count++;
System.Threading.Thread.Sleep(100);
}
if (asyncResult.IsCompleted)
{
_socket.Blocking = false;
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
// Set option that allows socket to receive out-of-band information in the data stream.
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, true);
_socket.ReceiveBufferSize = _socket.SendBufferSize = ServerSockets.ReceiveBuffer.RECV_BUFFER_SIZE;
}
return asyncResult.IsCompleted;
}
public void Create(Socket _socket)
{
try
{
ReceiveBuff = new ReceiveBuffer(Program.ServerConfig.Port_ReceiveSize);
Connection = _socket;
SetDHKey = false;
Alive = true;
LastReceive = Extensions.Time32.Now;
Client = Crypto = null;
TimerSubscriptions = new IDisposable[]
{
ThreadPoll.Subscribe<SecuritySocket>(ThreadPoll.ConnectionReceive, this, ThreadPoll.ReceivePool),
ThreadPoll.Subscribe<SecuritySocket>(ThreadPoll.ConnectionReview, this, ThreadPoll.GenericThreadPool)
};
}
catch (Exception e)
{
MyConsole.SaveException(e);
}
}
public void SetCrypto(Cryptography.TQCast5 Crypt)
{
if (!Program.ServerConfig.IsInterServer)
{
Crypto = Crypt;
}
}
public static void TryReview(SecuritySocket sock)
{
sock.CheckUp();
}
public void CheckUp()
{
if (Crypto != null)
{
if (Extensions.Time32.Now > LastReceive.AddSeconds(60 * 5))
this.Disconnect();
}
}
public int tstgg = 0;
object locckss = new object();
public unsafe void Send(Packet msg)
{
try
{
if (Alive)
{
lock (locckss)
{
byte[] _buffer = new byte[msg.Size];
if (Crypto != null)
Crypto.Encrypt(msg.Memory, 0, _buffer, 0, msg.Size);
else
fixed (byte* ptr = _buffer)
msg.memcpy(ptr, msg.Memory, msg.Size);
Connection.BeginSend(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(BeginSendCall), Connection);
}
}
}
catch (SocketException)
{
Disconnect();
}
catch (Exception e)
{
// MyConsole.WriteLine(e.ToString());
}
}
private void BeginSendCall(IAsyncResult ar)
{
try
{
if (Connection != null)
Connection.EndSend(ar);
}
catch (SocketException)
{
Disconnect();
}
catch (Exception e)
{
// MyConsole.WriteLine(e.ToString());
}
}
public ReceiveBuffer DHKeyBuffer = new ReceiveBuffer(1024, true);
public ReceiveBuffer EncryptedDHKeyBuffer = new ReceiveBuffer(1024, true);
public bool IsCompleteDHKey(out int type)
{
type = 0;
try
{
if (DHKeyBuffer.Length() < 8)
return false;
byte[] buffer = new byte[Packet.SealSize];
for (int x = 0; x < buffer.Length; x++)
buffer[x] = DHKeyBuffer.buffer[x + (DHKeyBuffer.Length() - Packet.SealSize)];
string Text = System.Text.ASCIIEncoding.ASCII.GetString(DHKeyBuffer.buffer);
bool accept = Text.Contains("TQClient");
if (!Text.EndsWith("TQClient"))
type = 1;
return accept;
}
catch (Exception e)
{
MyConsole.SaveException(e);
Disconnect();
return false;
}
}
public unsafe bool ReceiveDHKey()
{
try
{
if (Alive && WindowsAPI.ws2_32.CanRead(this))
{
int rec_type = 0;
if (!SetDHKey && Alive)
{
SocketError Socket_Error = SocketError.IsConnected;
int length = DHKeyBuffer.MaxLength() - DHKeyBuffer.Length();
if (length <= 0)
{
Disconnect();
return false;
}
int ret = Connection.Receive(DHKeyBuffer.buffer, DHKeyBuffer.Length(), length, SocketFlags.None, out Socket_Error);
if (ret > 0)
{
System.Buffer.BlockCopy(DHKeyBuffer.buffer, DHKeyBuffer.Length(), EncryptedDHKeyBuffer.buffer, EncryptedDHKeyBuffer.Length(), ret);
EncryptedDHKeyBuffer.AddLength(ret);
if (Crypto != null)
{
fixed (byte* ptr = DHKeyBuffer.buffer)
Crypto.Decrypt(DHKeyBuffer.buffer, DHKeyBuffer.Length(), ptr, DHKeyBuffer.Length(), ret);
}
DHKeyBuffer.AddLength(ret);
if (IsCompleteDHKey(out rec_type))
{
using (var rec = new RecycledPacket())
{
var stream = rec.GetStream();
stream.Seek(0);
fixed (byte* ptr = DHKeyBuffer.buffer)
stream.memcpy(stream.Memory, ptr, DHKeyBuffer.Length());
stream.Size = DHKeyBuffer.Length();
if (OnReceiveHandler != null)
OnReceiveHandler.Invoke(this, stream);
}
}
}
else if (ret <= 0 || Socket_Error == SocketError.ConnectionAborted)
{
Disconnect();
return false;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Disconnect();
}
return false;
}
public bool ReceiveBuffer()
{
if (Alive)
{
{
try
{
if (!SetDHKey && Crypto != null)
{
ReceiveDHKey();
}
else if (WindowsAPI.ws2_32.CanRead(this))
{
try
{
if (!Alive)
return false;
int available = Connection.Available;
if (available == 0)
{
Disconnect();
return false;
}
if (!Receive(available))
{
return false;
}
}
catch (Exception e)
{
MyConsole.SaveException(e);
Disconnect();
}
return true;
}
}
catch (Exception e) { Disconnect(); Console.WriteLine(e.ToString()); }
}
}
return false;
}
public unsafe bool HandlerBuffer()
{
int counts = 30;
while (true && counts > 0)
{
counts--;
if (!Alive)
return false;
try
{
if (!ConnectFull)
return false;
if (ReceiveBuff.Length() == 0)
return false;
int Length = (int)(ReceiveBuff.ReadHead() + (IsGameServer ? 8 : 0));
if (Program.ServerConfig.IsInterServer || OnInterServer)
Length += 8;
if (Length < 2)
return false;
if (Length > ServerSockets.ReceiveBuffer.HeadSize)
{
Disconnect();
return false;
}
if (Length > ReceiveBuff.Length())
return false;
LastReceive = Extensions.Time32.Now;
Packet Stream = PacketRecycle.Take();
Stream.Seek(0);
fixed (byte* ptr = ReceiveBuff.buffer)
{
Stream.memcpy(Stream.stream, ptr, Length);
if (Length < ReceiveBuff.Length())
{
fixed (void* next_buffer = &ReceiveBuff.buffer[Length])
{
Stream.memcpy(ptr, next_buffer, ReceiveBuff.Length() - Length);
}
}
Stream.Size = Length;
ReceiveBuff.DelLength(Length);
}
Stream.SeekForward(2);
if (OnReceiveHandler != null)
OnReceiveHandler.Invoke(this, Stream);
}
catch (Exception e) { Console.WriteLine(e.ToString()); }
}
return false;
}
public bool Receive(int available)
{
if (Alive)
{
SocketError Socket_Error = SocketError.IsConnected;
try
{
int length = ReceiveBuff.MaxLength() - ReceiveBuff.Length();
int receive_size = 0;
if (available > length)
receive_size = length;
else
receive_size = available;
if (receive_size == 0)
{
return false;
}
int ret = Connection.Receive(ReceiveBuff.buffer, ReceiveBuff.Length(), receive_size, SocketFlags.None, out Socket_Error);
if (ret > 0)
{
if (Crypto != null)
{
fixed (byte* ptr = ReceiveBuff.buffer)
Crypto.Decrypt(ReceiveBuff.buffer, ReceiveBuff.Length(), ptr, ReceiveBuff.Length(), ret);
}
ReceiveBuff.AddLength(ret);
return true;
}
else if (ret == 0)//<= 0 || Socket_Error == SocketError.ConnectionAborted)
{
Disconnect();
return false;
}
else//ret < 0
{
if (Socket_Error != SocketError.WouldBlock)
Disconnect();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.WriteLine(Socket_Error.ToString());
}
}
return false;
}
public int nPutBytes = 0;
public byte[] packet = null;
public object SynRoot = new object();
public void Disconnect()
{
lock (SynRoot)
{
if (Alive)
{
if (Server != null)
Server.Clients.Remove(this);
Alive = false;
if (TimerSubscriptions != null)
{
for (int i = 0; i < TimerSubscriptions.Length; i++)
if (TimerSubscriptions[i] != null)
TimerSubscriptions[i].Dispose();
}
try
{
WindowsAPI.ws2_32.shutdown(Connection.Handle, WindowsAPI.ws2_32.ShutDownFlags.SD_BOTH);
WindowsAPI.ws2_32.closesocket(Connection.Handle);
Connection.Dispose();
GC.SuppressFinalize(Connection);
}
catch (Exception e)
{
MyConsole.SaveException(e);
}
finally
{
if (OnDisconnect != null)
OnDisconnect.Invoke(this);
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Concurrent;
namespace Project_Terror_v2.ServerSockets
{
public class ServerSocket
{
private bool Alive = false;
private Socket Connection;
private string ServerAddresIP = "46.105.155.123";
public uint SPort;
public string ServerName = "WeConquer_EU";
private Action<SecuritySocket> ProcessConnection, ProcessDisconnect;
private Action<SecuritySocket, Packet> ProcessReceive;
private BruteforceProtection Bruteforce;
public Extensions.MyList<SecuritySocket> Clients = new Extensions.MyList<SecuritySocket>();
public ServerSocket(Action<SecuritySocket> _processConnection, Action<SecuritySocket, Packet> _procesreceive, Action<SecuritySocket> _processdisconnect)
{
ProcessConnection = _processConnection;
ProcessReceive = _procesreceive;
ProcessDisconnect = _processdisconnect;
Connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Initilize(ushort MaxBufferSend, ushort MaxBufferReceive, uint MaxAcceptConnections, uint MaxClientsConnections)
{
Connection.ReceiveBufferSize = 16384;
Connection.SendBufferSize = 16384;
}
public void Connect(string IpAddres, ushort port, string aServerName)
{
SPort = port;
ServerAddresIP = IpAddres;
ServerName = aServerName;
TryConnect(aServerName);
}
private void TryConnect(string servername)
{
//MyConsole.WriteLine("Server Trying connect to InterServer...");
Connection.BeginConnect(ServerAddresIP, (int)SPort, new AsyncCallback(ConnectCallback), null);
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Connection.EndConnect(ar);
Console.WriteLine("Socket connected to {0} successful !",
Connection.RemoteEndPoint.ToString());
Connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
// Set option that allows socket to receive out-of-band information in the data stream.
Connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, true);
Connection.ReceiveBufferSize = 4096;
Connection.SendBufferSize = 4096;
Alive = Connection.Connected;
if (Alive)
{
var client = new SecuritySocket(this, ProcessDisconnect, ProcessReceive);
client.Create(Connection);
if (ProcessConnection != null)
{
ProcessConnection(client);
}
}
}
catch
{
TryConnect(ServerName);
}
}
public void Open(string IpAddres, ushort port, int backlog)
{
Bruteforce = new BruteforceProtection();
Bruteforce.Init(10);
SPort = port;
ServerAddresIP = IpAddres;
Connection.Bind(new IPEndPoint(IPAddress.Any, port));
Connection.Listen((int)100);
Connection.Blocking = false;
Connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Connection.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
Connection.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
MyConsole.WriteLine("Listening on port : " + port.ToString());
Alive = true;
}
public void Accept()
{
try
{
if (Alive && Connection.Poll(0, SelectMode.SelectRead) && Connection.ProtocolType == ProtocolType.Tcp)
{
if (Connection.Poll(1, SelectMode.SelectError))
{
var close_socket = Connection.Accept();
WindowsAPI.ws2_32.shutdown(close_socket.Handle, WindowsAPI.ws2_32.ShutDownFlags.SD_BOTH);
WindowsAPI.ws2_32.closesocket(close_socket.Handle);
MyConsole.WriteLine("[Sockets] Error on socket Accept().");
return;
}
var socket = Connection.Accept();
string RemoteIP = (socket.RemoteEndPoint as IPEndPoint).Address.ToString();
if (!Bruteforce.IsBanned(RemoteIP))
{
SecuritySocket user = new SecuritySocket(this, ProcessDisconnect, ProcessReceive);
user.Create(socket);
Clients.Add(user);
//MyConsole.WriteLine("IP " + user.RemoteIp + " try to connect");
Bruteforce.AddWatch(user.RemoteIp);
if (ProcessConnection != null)
{
ProcessConnection.Invoke(user);
}
user.ConnectFull = true;
}
else
{
socket.Dispose();
}
}
}
catch (Exception e) { MyConsole.SaveException(e); }
}
public void Close()
{
if (Alive)
{
Alive = false;
Connection.Close(1);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_Terror_v2.ServerSockets
{
public class SocketThread
{
/*const int RECV_BUFFER_SIZE = 2048; // ?¦??³???×O¼?µ?BUF
const int SEND_BUFFER_SIZE = 4048; // ?¦??³???×O¼?µ?BUF*/
const int SOCKET_PROCESS_INTERVAL = 1;
private Extensions.ThreadGroup.ThreadItem ThreadItem;
private ServerSocket[] Sockets;
public SocketThread(string GroupName, params ServerSocket[] Sockets)
{
this.Sockets = Sockets;
ThreadItem = new Extensions.ThreadGroup.ThreadItem(SOCKET_PROCESS_INTERVAL, GroupName, Process);//asta inseamna totusi minim ping 40 da dar daca se folosesc 10 milisecunde cat trece prin toate... face 40-10 si face sleep(30);
}
public void Start()
{
ThreadItem.Open();
}
public void Process()
{
try
{
//ok deci aici e thread... am 40 ms in caz ca se folosesc 5... face sleep 35...
foreach (var _socket in Sockets)//sockets adica am .. 1 socket ptr acc server 1 socket ptr loader.. si 1 socket ptr game ...
{
try
{
if (_socket == null)//for inter server
continue;
_socket.Accept();
}
catch (Exception e)
{
MyConsole.SaveException(e);
}
/* foreach (var user in _socket.Clients.GetValues())
{
try
{
while (user.ReceiveBuffer())
{
}
user.HandlerBuffer();
}
catch
{
}
}*/
// var array = _socket.Sockets.ToArray();
/* foreach (var user in array)
{
try
{
while (user.ReceiveBuffer())
{
if (user.HandlerBuffer())
{
}
}
user.HandlerBuffer();
user.TrySend();
}
catch (Exception e) { MyConsole.WriteLine(e.ToString()); }
}*/
}
}
catch (Exception e) { MyConsole.WriteLine(e.ToString()); }
}
public void Close()
{
ThreadItem.Close();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Extensions;
using Extensions.Threading.Generic;
using Extensions.Threading;
namespace Project_Terror_v2
{
public static class ThreadPoll
{
#region Funcs
public static void Execute(Action action, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
GenericThreadPool.Subscribe(new Extensions.Threading.LazyDelegate(action, timeOut, priority));
}
public static void Execute<T>(Action<T> action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
GenericThreadPool.Subscribe<T>(new Extensions.Threading.Generic.LazyDelegate<T>(action, timeOut, priority), param);
}
public static IDisposable Subscribe(Action action, uint period = 1, ThreadPriority priority = ThreadPriority.Normal)
{
return GenericThreadPool.Subscribe(new Extensions.Threading.TimerRule(action, period, priority));
}
public static IDisposable Subscribe<T>(Action<T> action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
return GenericThreadPool.Subscribe<T>(new Extensions.Threading.Generic.TimerRule<T>(action, timeOut, priority), param);
}
public static IDisposable Subscribe<T>(Extensions.Threading.Generic.TimerRule<T> rule, T param, Extensions.Threading.StaticPool pool)
{
return pool.Subscribe<T>(rule, param);//BigBoSS not complete yet
}
public static IDisposable Subscribe<T>(Extensions.Threading.Generic.TimerRule<T> rule, T param)
{
return GenericThreadPool.Subscribe<T>(rule, param);//here where i stopped . complete work ya mo2mn
}
#endregion
public static TimerRule<ServerSockets.SecuritySocket> ConnectionReceive, ConnectionSend, ConnectionReview;
public static StaticPool GenericThreadPool;
public static StaticPool ReceivePool, SendPool;
public static void Create()
{
GenericThreadPool = new StaticPool(128).Run();
ReceivePool = new StaticPool(128).Run();
SendPool = new StaticPool(128).Run();
ConnectionReceive = new TimerRule<ServerSockets.SecuritySocket>(connectionReceive, 1);
ConnectionSend = new TimerRule<ServerSockets.SecuritySocket>(connectionSend, 1);
ConnectionReview = new TimerRule<ServerSockets.SecuritySocket>(_ConnectionReview, 300000, ThreadPriority.Lowest);
}
public static void connectionReceive(ServerSockets.SecuritySocket wrapper)
{
if (wrapper.ReceiveBuffer())
{
wrapper.HandlerBuffer();
}
}
public static void connectionSend(ServerSockets.SecuritySocket wrapper)
{
}
public static void _ConnectionReview(ServerSockets.SecuritySocket wrapper)
{
wrapper.CheckUp();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Extensions;
using System.Threading;
namespace Project_Terror_v2
{
public class ThreadPool
{
public static void Execute(Action action, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
GenericThreadPool.Subscribe(new Extensions.Threading.LazyDelegate(action, timeOut, priority));
}
public static void Execute<T>(Action<T> action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
GenericThreadPool.Subscribe<T>(new Extensions.Threading.Generic.LazyDelegate<T>(action, timeOut, priority), param);
}
public static IDisposable Subscribe(Action action, uint period = 1, ThreadPriority priority = ThreadPriority.Normal)
{
return GenericThreadPool.Subscribe(new Extensions.Threading.TimerRule(action, period, priority));
}
public static IDisposable Subscribe<T>(Action<T> action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal)
{
return GenericThreadPool.Subscribe<T>(new Extensions.Threading.Generic.TimerRule<T>(action, timeOut, priority), param);
}
public static IDisposable Subscribe<T>(Extensions.Threading.Generic.TimerRule<T> rule, T param, Extensions.Threading.StaticPool pool)
{
return pool.Subscribe<T>(rule, param);
}
public static IDisposable Subscribe<T>(Extensions.Threading.Generic.TimerRule<T> rule, T param)
{
return GenericThreadPool.Subscribe<T>(rule, param);
}
public static Extensions.Threading.StaticPool GenericThreadPool;
public static Extensions.Threading.StaticPool ReceivePool, SendPool, CheckUpConnectionReview;
public static Extensions.Threading.Generic.TimerRule<ServerSockets.SecuritySocket> ConnectionReceive, ConnectionReview, ConnectionSend;
public static void CreatePools()
{
#if TEST
GenericThreadPool = new Extensions.Threading.StaticPool(1).Run();
ReceivePool = new Extensions.Threading.StaticPool(1).Run();
SendPool = new Extensions.Threading.StaticPool(1).Run();
CheckUpConnectionReview = new Extensions.Threading.StaticPool(1).Run();
#else
GenericThreadPool = new Extensions.Threading.StaticPool(16).Run();
ReceivePool = new Extensions.Threading.StaticPool(64).Run();
SendPool = new Extensions.Threading.StaticPool(32).Run();
CheckUpConnectionReview = new Extensions.Threading.StaticPool(3).Run();
#endif
ConnectionReview = new Extensions.Threading.Generic.TimerRule<ServerSockets.SecuritySocket>(connectionReview, 1000, ThreadPriority.Lowest);
ConnectionReceive = new Extensions.Threading.Generic.TimerRule<ServerSockets.SecuritySocket>(connectionReceive, 1, ThreadPriority.Highest);
ConnectionSend = new Extensions.Threading.Generic.TimerRule<ServerSockets.SecuritySocket>(connectionSend, 1, ThreadPriority.Highest);
Game.MsgMonster.PoolProcesor.CreatePools();
Client.PoolProcesor.CreatePools();
Role.GameMap.CreatePool();
}
private static void connectionReview(ServerSockets.SecuritySocket wrapper)
{
ServerSockets.SecuritySocket.TryReview(wrapper);
}
private static void connectionReceive(ServerSockets.SecuritySocket wrapper)
{
ServerSockets.SecuritySocket.TryReceive(wrapper);
}
private static void connectionSend(ServerSockets.SecuritySocket wrapper)
{
ServerSockets.SecuritySocket.TrySend(wrapper);
}
public static void ServerInfo()
{
MyConsole.Title = "Players Online : " + Database.Server.GamePoll.Count + " Queue Packets " + ServerSockets.PacketRecycle.Count;
}
}
}
الذين يشاهدون محتوى الموضوع الآن : 3 ( الأعضاء 0 والزوار 3) | |
|
الموضوع | كاتب الموضوع | المنتدى | مشاركات | آخر مشاركة |
Gui [alex Source] | Tefa | تطوير سيرفرات كونكر | 67 | 2024-11-01 01:44 AM |
مشكله في الاي بوله في السيرفر | Amr Khalid | مشكلات السيرفيرات كونكر الشخصيه | 10 | 2020-05-04 05:39 PM |
الاج عندي في سورس رايزو راهيب و مش لاقي حل | محمودمحمدسالم | مشكلات السيرفيرات كونكر الشخصيه | 9 | 2020-03-20 05:42 AM |
مشكلة الاج الخفيف لما الاكونت يموت | MRonlineGvrix | مشكلات السيرفيرات كونكر الشخصيه | 4 | 2020-02-29 01:37 PM |
npc EpicWeapons[Source Alex] | Tefa | تطوير سيرفرات كونكر | 6 | 2019-11-25 10:18 PM |