namespace Otaku.Socketservers { using Otaku; using Otaku.Virtual.Users; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; public static class gameSocketServer { private static int _acceptedConnections; private static HashSet _activeConnections; private static int _maxConnections; private static int _Port; private static Socket socketHandler; private static void connectionRequest(IAsyncResult iAr) { try { int item = 0; for (int i = 1; i < _maxConnections; i++) { if (!_activeConnections.Contains(i)) { item = i; break; } } if (item > 0) { Socket connectionSocket = ((Socket) iAr.AsyncState).EndAccept(iAr); Out.WriteLine(string.Concat(new object[] { "Accepted connection [", item, "] from ", connectionSocket.RemoteEndPoint.ToString().Split(new char[] { ':' })[0] })); _activeConnections.Add(item); _acceptedConnections++; new virtualUser(item, connectionSocket); } } catch { } socketHandler.BeginAccept(new AsyncCallback(gameSocketServer.connectionRequest), socketHandler); } internal static void freeConnection(int connectionID) { if (_activeConnections.Contains(connectionID)) { _activeConnections.Remove(connectionID); Out.WriteLine("Flagged connection [" + connectionID + "] as free."); } } internal static bool Init(int bindPort, int maxConnections) { _Port = bindPort; _maxConnections = maxConnections; _activeConnections = new HashSet(); socketHandler = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Out.WriteLine("Starting up asynchronous socket server for game connections for port " + bindPort + "..."); try { socketHandler.Bind(new IPEndPoint(IPAddress.Any, bindPort)); socketHandler.Listen(0x19); socketHandler.BeginAccept(new AsyncCallback(gameSocketServer.connectionRequest), socketHandler); Out.WriteLine("Asynchronous socket server for game connections running on port " + bindPort); Out.WriteLine("Max simultaneous connections is " + maxConnections); return true; } catch { Out.WriteError("Error while setting up asynchronous socket server for game connections on port " + bindPort); Out.WriteError("Port " + bindPort + " could be invalid or in use already."); return false; } } internal static int acceptedConnections { get { return _acceptedConnections; } } internal static int maxConnections { get { return _maxConnections; } set { _maxConnections = value; } } } }