//read updates from clients public static void readUpdate(IAsyncResult ar) { Socket handler = null; TimeoutState state = (TimeoutState)ar.AsyncState; try { //Console.WriteLine("Entered timeout readupdate"); //retreive the state object and socket handler = state.ClientSocket; ar.AsyncWaitHandle.WaitOne(); if (handler.EndReceive(ar) == 0) { Console.WriteLine("\nPlayer disconnected timeout readUpdate"); if (state.Timeout != null) { state.cleanup(); } return; } //Console.WriteLine("Received ack\n"); //when recieve ack, restart timout state.resetTimeout(); handler.Send(state.TestCon); handler.BeginReceive(state.TestCon, 0, UPDATE_SIZE, 0, new AsyncCallback(readUpdate), state); } //end communications gracefully if player disconnects catch (Exception) { //Console.WriteLine(e.ToString()); Console.WriteLine("\nPlayer disconnected timeout readUpdate"); if (state.Timeout != null) { state.cleanup(); } } }
//async method for connecting to clients public static void connect(IAsyncResult ar) { TimeoutState state = new TimeoutState(); try { //connection finished, allow others to connect connectionFound.Set(); Console.WriteLine("\nPlayer connected timeout manager"); //get user id first, follow similar procedure //TimeoutState state = new TimeoutState(null, null, null); //get socket for client Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); //MAKE SURE TO ADD THIS TO CLIENT SIDE byte[] id = new byte[16]; handler.Receive(id, 16, 0); state.ClientID = new Guid(id); state.ClientSocket = handler; //Console.WriteLine("loc 0\n"); ClientState addSocket; lock (ConnectedPlayers.DICTIONARY_LOCK) { if (ConnectedPlayers.playerDetails.TryGetValue(state.ClientID, out addSocket)) { addSocket.TimeoutSocket = handler; } else { addSocket = new ClientState(null, null, null, handler); ConnectedPlayers.playerDetails.Add(state.ClientID, addSocket); } } //Console.WriteLine("loc 1"); state.startTimeout(); //Console.WriteLine("loc 2"); //start recieving client connection confirmations handler.BeginReceive(state.TestCon, 0, UPDATE_SIZE, 0, new AsyncCallback(readUpdate), state); } //catch connection errors catch (Exception e) { Console.WriteLine(e.ToString()); Console.WriteLine("\nPlayer disconnected timeout connect"); if (state != null) { state.cleanup(); } } }