public void Connect(int aPort, IPAddress Ip, string userName, string password, string nick)
{
int attempts = 5;
_nick = nick;
// TODO: validar esse objeto, pois após a desconexão ocorre o dispose() dele
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while (!_clientSocket.Connected && attempts > 0)
{
try
{
OnRaiseMessage(new MessageEventArgs(String.Format("Attempt {0} to connect at server {1}:{2}", attempts, Ip.MapToIPv4().Address, aPort)));
_clientSocket.Connect(Ip ,aPort);
OnRaiseMessage(new MessageEventArgs("Connected!"));
//solicita autenticação
Authenticate(userName, password);
//inicia recebimento assíncrono de mensagens
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _clientSocket);
}
catch (Exception ex)
{
OnRaiseMessage(new MessageEventArgs("Connection failed."));
Thread.Sleep(1000);
attempts--;
}
}
}