using System; using System.Collections; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace Blizzard.Connections { class SocketConnection { private static Socket SocketListen; private static Socket[] SocketWork = new Socket[10]; private static Hashtable Connections = new Hashtable(); internal static int AlreadyConnections = 0; internal static int AcceptedConnections = 0; internal static int GameId = 0; private static Thread Checker = new Thread(new ThreadStart(WaitForSockets)); private static int TCP_PORT; private static string TCP_IP; private static string IPv; private static IPAddress IP; private static GetData ConfigD; public static void End() { Checker.Abort(); AlreadyConnections = 0; AcceptedConnections = 0; SocketListen.Close(); } public static void InitializeConnections() { try { ConfigD = new GetData("configuration.cnf"); TCP_IP = ConfigD.data["tcp.ip"]; TCP_PORT = int.Parse(ConfigD.data["tcp.port"]); IPv = ConfigD.data["ip.type"]; if (IPv == "IPv6") // We need to process the IPNetwork 6 Sockets D: ¡use this! SocketListen = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); else // or not... USE THIS NORMAL WAY! SocketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint LocalHost = new IPEndPoint(IPAddress.Any, TCP_PORT); SocketListen.ReceiveTimeout = 6000; SocketListen.SendTimeout = 6000; SocketListen.NoDelay = true; SocketListen.LingerState = new LingerOption(true, 1); SocketListen.Bind(LocalHost); //SocketListen.Connect(LocalHost); SocketListen.Listen(10000); BlizzardSystem.WriteLine("Blizzard connected to the PORT: " + TCP_PORT + "; IP: " + TCP_IP + "..."); Checker.Start(); WaitForNextConnection(); } catch { BlizzardSystem.WriteLine("The emulator can't initialize, try later please..."); } } private static void WaitForNextConnection() { try { SocketListen.BeginAccept(new AsyncCallback(OnConnection), SocketListen); } catch (Exception e) { BlizzardSystem.WriteLine("failed: " + e.ToString()); } } private static void OnConnection(IAsyncResult Async) { try { Socket FromClient = ((Socket)Async.AsyncState).EndAccept(Async); string ClientIP = FromClient.RemoteEndPoint.ToString().Split(':')[0]; new Game(FromClient, GameId); GameId++; } catch (Exception e) { BlizzardSystem.WriteLine("Sockets fail during execution: " + e.Message); } finally { SocketListen.BeginAccept(new AsyncCallback(OnConnection), SocketListen); } } private static void WaitForSockets() { while (true) { Hashtable TMP = Connections; foreach (Game EndPoint in TMP.Values) { if (!EndPoint.SocketsActive) { try { EndPoint.Disconnect(); } catch { } } } TMP.Clear(); Thread.Sleep(1); } } } }