Bi-Directional Communication - How to get status?

Asked

Viewed 56 times

2

Library that I use: https://github.com/rdavisau/sockets-for-pcl

Follows 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 enter address Ip Server wrong, for this, I need to check the connection status. The property IsCompleted always returns as false, some solution of how I can get connection status ?

  • What is the package of TcpSocketClient()?

  • @LeandroAngelo https://github.com/rdavisau/sockets-for-pcl

1 answer

1


You are calling an asynchronous method, waiting 5 seconds and then trying to read an attribute that may not be reflecting your real state. And you’re also not capturing 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);
        }

    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.