I am trying to do this in order not to crash the application while waiting for the server to accept the connection. I saw what you can do with async
and await
.
But when trying to use them to wait for the connection without crashing, the program returns infinitely a Exception
:
Exception thrown: 'System.NullReferenceException' in MessengerTcpIp.exe
And it gets all stuck. It gives this problem at the time of waiting for the server to respond.
Code:
private async void ConnectServer()
{
try
{
server = IPAddress.Parse(serverAddr.Text);
port = 12303;
user = new TcpClient();
connBtn.Text = "Aguardando conexão";
await user.ConnectAsync(server, port);
strWriter = new StreamWriter(user.GetStream());
strReader = new StreamReader(user.GetStream());
strWriter.AutoFlush = true;
StrWriter.WriteLine(email.Text);
StrWriter.WriteLine(password.Text);
var SvResponse = await strReader.ReadLineAsync();
if(SvResponse == "ok")
{
userInfo.AppendText("Conectado com sucesso.");
connBtn.Text = "Conectado";
}
else
{
MessageBox.show("Falha ao se conectar.");
}
}
catch (Exception err)
{
MessageBox.Show("Exception:" + err.Message, "Erro de conexão.", MessageBoxButtons.OK, MessageBoxIcon.Error);
connBtn.Text = "Conectar";
}
}
Calling button:
private void Conectar_Click(object sender, EventArgs e)
{
ConnectServer();
}