using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections; namespace CELobbyServer { class MainServer { public static Hashtable connections; public static IDictionaryEnumerator enumerator; public static Socket server; public static ArrayList GetDataList = new ArrayList(); public static ManualResetEvent ConnectedState = new ManualResetEvent(false); public MainServer() { connections = new Hashtable(Config.MAX_CLIENTS); IPEndPoint localEndPoint = new IPEndPoint(Config.SERVER_IP, Config.SERVER_PORT); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { //define listen and connect threads Thread ConnectionsThread = new Thread(HandleIncConnections); Thread DataThread = new Thread(HandleIncData); //start the server server.Bind(localEndPoint); server.Listen(1000); GetDataList.Add(server); //start the threads for listening for new clients and new data enumerator = connections.GetEnumerator(); ConnectionsThread.Start(); DataThread.Start(); } catch (Exception e) { Console.WriteLine(e); } } private void HandleIncConnections() { while (true) { NewConnectionListen(); } } private void HandleIncData() { while (true) { Socket.Select(GetDataList, null, null, 100); if (GetDataList.Count > 1) { int a; for (a = 0; a < GetDataList.Count; a++) { Socket soc = (Socket)GetDataList[a]; if (soc.Available > 0) { WaitForData(soc); } } } try { enumerator = connections.GetEnumerator(); } catch { } while (enumerator.MoveNext()) { User CheckUser = (User)enumerator.Key; Socket soc = CheckUser.ConnectedSocket; GetDataList.Add(soc); } enumerator.Reset(); GetDataList.Add(server); } } private static void NewConnectionListen() { ConnectedState.Reset(); server.BeginAccept(new AsyncCallback(NewConnectionCallback), server); ConnectedState.WaitOne(); } private static void NewConnectionCallback(IAsyncResult ar) { Socket soc = (Socket)ar.AsyncState; User UserData = new User(soc.EndAccept(ar)); connections.Add(UserData, null); GetDataList.Add(soc); Console.WriteLine("New Connection: " + UserData.ConnectedSocket.RemoteEndPoint.ToString()); ConnectedState.Set(); } byte[] m_DataBuffer = new byte[10]; IAsyncResult m_asynResult; public AsyncCallback pfnCallBack; public Socket m_socClient; // create the socket... public void WaitForData(Socket soc) { m_socClient = soc; if (pfnCallBack == null) pfnCallBack = new AsyncCallback(OnDataReceived); // now start to listen for any data... m_asynResult = m_socClient.BeginReceive(m_DataBuffer, 0, m_DataBuffer.Length, SocketFlags.None, pfnCallBack, null); } public void OnDataReceived(IAsyncResult asyn) { //end receive... int iRx = 0; iRx = m_socClient.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(m_DataBuffer, 0, iRx, chars, 0); System.String szData = new System.String(chars); Console.WriteLine(szData); } } }