Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

sockets - How can I convert string to utf8 in Dart?

I am using aqueduct web api framework to support my flutter app. In my api backend I need to connect local network socket services. My problem is that I can't return the exact string (in tr). So, How can I convert string to utf8 in Dart?

Example:

@httpGet
Future<Response> getLogin() async {
  Socket.connect('192.168.1.22’, 1024).then((socket) async {
    socket.listen((data) {
      // Expected return is: 1:_:2:_:175997:_:N?YAZ? TOROS
      print(new String.fromCharCodes(data).trim());
      xResult = new String.fromCharCodes(data).trim();
      print("xResult: $xResult");
    }, onDone: () {
      print("Done");
      socket.destroy();
    });

    socket.write('Q101:_:49785:_:x
');
  });

  return new Response.ok(xResult);
}

The return is not in TR-tr language format.

Return text looks like: 1::2::175997:_:NYYAZY TOROS

Correct must be: 1::2::175997:_:N?YAZ? TOROS

UPDATE:

  1. xResult = new String.fromCharCodes(data).trim();
  2. print(xResult);
  3. responseBody = xResult.transform(utf8.decoder);
  4. print(responseBody);

I can print the xResult but cannot print the responseBody after trying convert to UTF8

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import 'dart:convert' show utf8;

var encoded = utf8.encode('Lorem ipsum dolor sit amet, consetetur...');
var decoded = utf8.decode(encoded);

See also https://api.dartlang.org/stable/1.24.3/dart-convert/UTF8-constant.html

There are also encoder and decoder to be used with streams

File.openRead().transform(utf8.decoder).

See also https://www.dartlang.org/articles/libraries/converters-and-codecs#converter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...