public void Connect(Action <CommunicationException> connectionFailureHandler, Action <IMessage> messageHandler)
 {
     while (!_connectedToServer)
     {
         _tcpConnection?.CloseConnection();
         try
         {
             _connectDone.Reset();
             var socket = new Socket(_ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
             _tcpConnection = new ClientTcpConnection(-1, socket, connectionFailureHandler, _keepAliveTimeout,
                                                      _messageDeserializer, messageHandler);
             socket.BeginConnect(_ipEndPoint, ConnectCallback, socket);
             _connectDone.WaitOne();
         }
         catch (Exception e)
         {
             ConnectionError.PrintUnexpectedConnectionErrorDetails(e);
             throw;
         }
     }
     Console.WriteLine("Connected to CS");
     StartReading();
 }
 public void CloseConnection()
 {
     _tcpConnection.CloseConnection();
     _connectFinalized.Reset();
     _connectedToServer = false;
 }