Bidirectional Communication - How to get status?

2

Library that I use: link

Following code:

Server:

static async Task Run()
{
    var listenPort = 11000;
    var listener = new TcpSocketListener();
    listener.ConnectionReceived += async (sender, args) =>
    {
        var client = args.SocketClient;
        var reader = new StreamReader(client.ReadStream);
        var data = await reader.ReadLineAsync() + "\n";
        var bytes = Encoding.UTF8.GetBytes(data);
        await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
        await client.WriteStream.FlushAsync();
    };

    await listener.StartListeningAsync(listenPort);
}

Client:

static async Task Run()
{
    var address = "127.0.0.1.2.4";
    var port = 11000;

    var client = new TcpSocketClient();
    var connectionTask = client.ConnectAsync(address, port);
    connectionTask.Wait(5000);

    if (connectionTask.IsCompleted)
    {
        //
    }

    var bytes = Encoding.UTF8.GetBytes("Olá mundo\n");
    await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
    await client.WriteStream.FlushAsync();

    var reader = new StreamReader(client.ReadStream);
    var data = await reader.ReadLineAsync();
    Console.WriteLine(data);
}

Sometimes you can type the wrong Ip Server address, for this, I need to check the status of the connection. Does IsCompleted property always return as false , some solution how can I get connection status?

    
asked by anonymous 19.03.2018 / 20:59

1 answer

1

You are calling an asynchronous method, waiting 5 seconds and then trying to read an attribute that may not be reflecting its real state. And you're also not catching the error while trying to connect. see the changed method

public async Task Run()
{
    var address = "127.0.0.1.2.8";
    var port = 11000;

    using (var client = new TcpSocketClient())
    {
        try
        {
            await client.ConnectAsync(address, port);

            if (client.Socket.Connected)
            {
                var bytes = Encoding.UTF8.GetBytes("Olá mundo\n");
                await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
                await client.WriteStream.FlushAsync();

                var reader = new StreamReader(client.ReadStream);
                var data = await reader.ReadLineAsync();
                Console.WriteLine(data);
            }
        }catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }

    }
}
    
19.03.2018 / 21:06