بسـم آللهـ الـرحمـن آلـرحيـم ,, 😀
بآلنسـبهـ للـنآس اللـي بتـموت فـ الهـري كتـيـر
واللـ يقـولكـ انـ حلـ مشـكلهـ اللآج مشـ كآملـهـ يـبقي بيـضحكـ عليـك لآنـي عآملـهآ بـريكـ بـوينتـ ودهـ حلـهآ ثآنيـآ ءنـآ حآلـهآ بـطريقهـ تآنيهـ عـندي ووبيعـ الحـل دهـ بسـ النآس بـتقولكـ بيـجيبـ آيـرور فـ كلآس
TheardPoll.cs !
والنـآس اللـي تـعبتـ يـنآري فـ الكـوبي بيـستـ للـحلـ بـقآ وتـقولكـ ءحـنآ حلـينهـ بـقآ لآ آحـبب مـن نـهردآ مفيـشـ بيـعـ بـقآ هـتقولـي ليـهـ هـقولكـ بلآحهـ بـقآ xD
وءنـآ نـآوي آضـحي بـقيـ بـ الحـل بتآعـي للـنآسـ اللـي ببيـعهـ بـمنآسـبهـ عيـد ميلآديـ نخشـ فـ الآضآفهـ علـطول 😀 !
خشـ فـ المـسآر ..
1 |
Game/MsgMonster |
آفـتحـ كلآس !
1 |
PoolProcesor.cs |
بـدلهـ بـ !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
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(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(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(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); } } } } |
فـ المسـآر ..
1 |
ServerSockets |
آفـتحـ كلآس !
1 |
BruteforceProtection.cs |
بدلهـ بـ !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
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; } } } |
آفـتحـ كلآس !
1 |
ConcurrentPacketQueue.cs |
بدلهـ بـ !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
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; } } } } |
آعـمل كلآسـ جـديد فـ فـولدر ServerSockets ,, !
بآسـم LoginController.cs !
وضيـف فيـهـ دهـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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 { } } } } |
خشـ عـ كلآس Packet.cs !
وبدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
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 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(ms); } return obj; } public T ProtoBufferDeserialize(T obj, byte[] packet) { using (var ms = new System.IO.MemoryStream(packet)) { obj = ProtoBuf.Serializer.Deserialize(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); } } } |
خشـ عـ كلآس PacketRecycle.cs !
بدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
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 bin = new ConcurrentQueue(); 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); } } } |
بـعد كـدآ خشـ عـ كلآس ReceiveBuffer.cs !
بدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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; } } } |
خشـ عـ كلآس SecuritySocket.cs !
بدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 |
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 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 _OnDisconnect, Action<SecuritySocket, Packet> _OnReceiveHandler) { Server = serversocket; OnReceiveHandler = _OnReceiveHandler; OnDisconnect = _OnDisconnect; } public SecuritySocket(Action _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(ThreadPoll.ConnectionReceive, this, ThreadPoll.ReceivePool), ThreadPoll.Subscribe(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); } } } } } } |
خشـ عـ كلآس ServerSocket.cs !
بدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
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 ProcessConnection, ProcessDisconnect; private Action<SecuritySocket, Packet> ProcessReceive; private BruteforceProtection Bruteforce; public Extensions.MyList Clients = new Extensions.MyList(); public ServerSocket(Action _processConnection, Action<SecuritySocket, Packet> _procesreceive, Action _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); } } } } |
بـعد كـدآ خشـ عـ كلآس SocketThread.cs !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
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; // Ó¦ÓóÌÐò×Ô¼ºµÄBUF const int SEND_BUFFER_SIZE = 4048; // Ó¦ÓóÌÐò×Ô¼ºµÄ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(); } } } |
بـعد كـدآ خشـ عـ كلآس ThreadPoll.cs !
بدلهـ بـ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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(Action action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal) { GenericThreadPool.Subscribe(new Extensions.Threading.Generic.LazyDelegate(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(Action action, T param, uint timeOut = 0, ThreadPriority priority = ThreadPriority.Normal) { return GenericThreadPool.Subscribe(new Extensions.Threading.Generic.TimerRule(action, timeOut, priority), param); } public static IDisposable Subscribe(Extensions.Threading.Generic.TimerRule rule, T param, Extensions.Threading.StaticPool pool) { return pool.Subscribe(rule, param);//BigBoSS not complete yet } public static IDisposable Subscribe(Extensions.Threading.Generic.TimerRule rule, T param) { return GenericThreadPool.Subscribe(rule, param);//here where i stopped . complete work ya mo2mn } #endregion public static TimerRule 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(connectionReceive, 1); ConnectionSend = new TimerRule(connectionSend, 1); ConnectionReview = new TimerRule(_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(); } } |