Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Weird problem with TcpClient and NetworkStream: it never fails?

$
0
0

I'm working on a cross-platform app using Xamarin. The app is a client connected to a server, communicating over a custom TCP based protocol. So far most of the work and testing has been done on the iOS app.

The problem I've run into on the Android app is that I cannot detect that the connection is broken. After the connection is opened I keep a reference to the NetworkStream retrieved by calling currentNetworkStream = tcpClient.GetStream();

The write method looks like this:

private async Task SendAsync(byte[] data)
{
    if (currentNetworkStream != null &&
        currentNetworkStream.CanWrite)
    {
        await mutex.WaitAsync().ConfigureAwait(false);
        try
        {
            await currentNetworkStream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
            await currentNetworkStream.FlushAsync();
        }
        catch (Exception ex)
        {
            log.ErrorException("Error writing to Network Stream", ex);
            throw;
        }
        finally
        {
            mutex.Release();
        }
    }
    else if (currentNetworkStream == null)
    {
        log.Warn("Network Stream is null");
    }
    else if (!currentNetworkStream.CanWrite)
    {
        log.Warn("Network Stream CanWrite = false");
    }
}

The code works just fine - and I can communicate with the server as expected.

However, if I kill the server, I can't detect the broken connection. None of the WriteAsync or FlushAsync methods throw exception (like they do on iOS). All properties on the currentNetworkStream instance are OK (CanWrite is true).

Are there any network related settings I'm missing on Android that I need to set in order to get the expected behavior? All method calls return (i.e. the tasks complete just fine and the code execution continues as if the client was still connected).

EDIT: Tested on Android simulator.


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>