private void Task_OnConnectionAccepted(Socket socket)
        {
            Console.WriteLine(String.Format("Connection to {0} accepted.", socket.RemoteEndPoint));

            // If the registrant was already registered
            if (Clients.FindAll(registrant => registrant.RemoteEndPoint == socket.RemoteEndPoint).Any())
            {
                // Remove the registrant
                Clients.RemoveAll(registrant => registrant.RemoteEndPoint == socket.RemoteEndPoint);
            }

            // Register the registrant
            var newRegistrant = new Client(socket);
            Clients.Add(newRegistrant);

            Task_BeginReceive(newRegistrant);
            
            // Invoke the event
            if (OnConnectionAccepted != null)
                OnConnectionAccepted(this, new ConnectionAcceptedEventArgs() { Socket = socket } );
        }
        private void Task_OnReceiveCompleted(int numBytesRead, Client registrant)
        {
            // Build back our MessageReader
            var reader = new BufferValueReader(registrant.Buffer);
            var message = new Message();
            message.ReadPayload(reader);
            reader.Position = 0;

            Console.WriteLine(String.Format("Received a {0} byte {1}Message from {2}.", numBytesRead, message.MessageType, registrant.Socket.RemoteEndPoint));

            if (OnMessageReceived != null)
                OnMessageReceived(this, new MessageReceivedEventArgs() { From = (IPEndPoint) registrant.RemoteEndPoint, MessageReader = reader, MessageType = message.MessageType });
        }
 private void Task_BeginReceive(Client registrant)
 {
     var task = Task.Factory.FromAsync<Int32>(registrant.Socket.BeginReceive(registrant.Buffer, 0, registrant.Buffer.Length, SocketFlags.None, null, null), registrant.Socket.EndReceive);
     task.ContinueWith(nextTask =>
     {
         try
         {
             Task_OnReceiveCompleted(task.Result, registrant);
             Task_BeginReceive(registrant); // Receive more data
         }
         catch (Exception ex)
         {
             var exceptionMessage = (ex.InnerException != null) ? ex.InnerException.Message : ex.Message;
             Console.WriteLine(exceptionMessage);
             ShutdownAndClose();
         }
     }, TaskContinuationOptions.OnlyOnRanToCompletion);
 }