Flutter/Dart socket communication, characters encoding issue

833

Solution 1

I found the solution. Here it is:

Code for the Client:

Socket.connect('127.0.0.1', 8080).then((socket) {
   String data = 'Les élèves regardent par la fenêtre';

   socket.encoding = utf8;   // <== force the encoding
   socket.write(data);
   print("sent: $data");
}).catchError(print);

Code for the Server:

ServerSocket.bind('127.0.0.1', 8080).then((ServerSocket socketServer) {
    socketServer.listen((Socket socket) {
       socket.listen((List<int> data){
          String result = utf8.decode(data);
          print('received: $result'); 
        });
    });
}).catchError(print);

The solution consists of "forcing" the encoding to utf8

Thanks for your help.

Solution 2

You should try using ut8.encode when writing the data, and utf8.decode when reading it on the other side.

Share:
833
boeledi
Author by

boeledi

Updated on December 17, 2022

Comments

  • boeledi
    boeledi over 1 year

    For a proof of concept where 2 applications, written in Flutter and running on the same device, need to exchange information, I am using the 'dart:io' Sockets.

    One of the 2 applications implements a SocketServer to receive the information and the other initializes the sockets communication.

    From a connection perspective, this is working fine, using the following code:

    Code of the server:

    ServerSocket.bind('127.0.0.1', 8080).then((ServerSocket socketServer) {
        socketServer.listen((Socket socket) {
           socket.listen((List<int> data){
              String result = String.fromCharCodes(data);
              print('received: $result'); 
            });
        });
    }).catchError(print);
    

    Code of the client:

    Socket.connect('127.0.0.1', 8080).then((socket) {
       String data = 'Les élèves regardent par la fenêtre';
       socket.write(data);
       print("sent: $data");
    }).catchError(print);
    

    However, when I try to send a String which contains accentuated characters, I have the following outcome:

    sent: Les élèves regardent par la fenêtre
    received: Les élèves regardent par la fenêtre
    

    This looks like an encoding related issue but I haven't yet been able to solve it.

    Would anybody have any idea how to proceed to have this working? Thanks

    • tomerpacific
      tomerpacific about 4 years
      Have you considered using the Encoding class?