Search code examples
flutterdartsocketstcp

How to use Socket in Flutter apps?


I'm trying to connect to a device over TCP socket, write data and read response from socket. I made simple testing with c#, which works as expected. C# code, that works well:

using (TcpClient client = new TcpClient(terminal.server_IP, terminal.port))
        {
            try
            {
                using (NetworkStream stream = client.GetStream())
                {
                    try
                    {
                        stream.ReadTimeout = 5000;

                        byte[] msg = new byte[10];
                        msg[0] = 1;
                        msg[1] = 1;
                        msg[2] = 0;
                        msg[3] = 5;
                        msg[4] = 70;
                        msg[5] = 82;
                        msg[6] = 82;
                        msg[7] = 84;
                        msg[8] = 67;
                        msg[9] = 81;

                        stream.Write(msg, 0, msg.Length);

                        int i = 0;
                        while (!stream.DataAvailable && i < 5)
                        {
                            await Task.Delay(100);
                            i++;
                        }

                        byte[] data = new byte[4096];
                        int bytes = stream.Read(data, 0, data.Length);
                        msg = new byte[bytes];
                        string tst = Encoding.GetEncoding("Windows-1250").GetString(data, 2, data[1]);
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }
            finally
            {
                client.Close();
            }
        }

i need to transform this into a flutter application, i made the code, where the data don't get back to listen. Flutter code:

try {
  socket?.destroy();
  socket = await Socket.connect(serverIP, serverPort).catchError((error) {
    print('error $e');
  });

  socket!.listen((data) {
    print('data');
  }, onError: (e) {
    print('error');
    socket!.destroy();
  }, onDone: () {
    print('done');
    socket!.destroy();
  }, cancelOnError: false);

  List<int> message = [1, 1, 0, 5, 70, 82, 82, 84, 67, 81];
  socket!.write(message);
} catch (e) {
  print('errors: $e');
}

it don't throws any errors, everyhing runs, but i can't read the data from the device. Any advice what i'm doing wrong?


Solution

  • So, after a couple of days tying, i figured that the problem was sthe socket!.write(message). I replaced it with socket!.add(message);, not it works as expected.

    Leaving it here for evidence, to save time for someone in the future who has the same problems.