TcpClient object does not close in MAUI on Android

I have 2 applications. Server and client. The server is written in C# Console application and it describes the logic for listening to all incoming connections using TcpClient. I also use StreamWriter and StreamReader to read received messages and send them. The client is implemented in the MAUi application on Android.

On the client side, I created several pages that perform the login, welcome, logout, and message sending logic.

On one of the client pages I create a TcpClient object and connect to the server. Successfully. I am sending a link to the next page. On the next page, when interacting with this client, messages are sent and received through the StreamWriter and StreamReader. However, when you try to close the streams and/or the client itself, when checking it turns out that it is empty, although at this moment the connection hangs.

//server
try
{
  if (client.Connected)
  {
    message = await Reader.ReadLineAsync();
    if (message == null) continue;
    message = $"{userName}: {message}";
    Console.WriteLine(message);
    File.AppendAllText(path, message + Environment.NewLine);
    await server.BroadcastMessageAsync(message, Id);
  }
  else
  {
    throw new Exception();
  }
}
catch
{
  message = $"{userName} closed the connection";
  Console.WriteLine(message);
  File.AppendAllText(path, message + Environment.NewLine);
  await server.BroadcastMessageAsync(message, Id);
  break;
}               
//client first page
public TcpClient client  = new TcpClient();
try
{
  using (var cts = new CancellationTokenSource())
  {
    cts.CancelAfter(timeout);
    var connectTask = client.ConnectAsync(host, port);
    var completedTask = await Task.WhenAny(connectTask, Task.Run(() => cts.Token.WaitHandle.WaitOne()));

    if (completedTask == connectTask)
    {
      await connectTask;
      var chatPage = new ChatPage(client);
      Application.Current.MainPage = chatPage;
    }
    else
    {
      Application.Current.MainPage = new Disconnect(client);
      return; 
    }
  }
}
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.ConnectionRefused)
{
  Application.Current.MainPage = new Disconnect(client);
  client.Close();
  return;
}
//client second page

//I receive a TcpClient object through the constructor, create a static private TcpClient client and assign the object received from the constructor to it

if (client.Connected)
{
  Writer?.Close();
  Reader?.Close();
  client.Close();
}
else
{
  DisplayAlert("Error", "ok", "оk");
}

Upvotes: 0

Views: 109

Answers (0)

Related Questions