Flutter send json to websocket server as bytes?

3,006

You can get a JSON string in Dart

import 'dart:convert';

...

var jsonString = json.encode(data);

and get bytes of the string using

var bytes = jsonString.codeUnits; 
Share:
3,006
Nicholas Jela
Author by

Nicholas Jela

I am an engineer in China, I have asked many question...

Updated on December 05, 2022

Comments

  • Nicholas Jela
    Nicholas Jela over 1 year

    I have a JSON like message like this:

      static getHiMsg(String token, String sender) {
       var msg = {
            "token": token,
            "user_addr": sender,
            "ua": "dart/fluter-v0.0.1",
            "device": "Phone",
            "location": "Hunan"
        };
        var outMsg = {
            "msg_type": "hi",
            "payload": msg
        };
        return outMsg;
      }
    

    and I wanna send this message to websocket server which only deal with json request, if a plain text or wrong format json, it will refuse connection.

    Here is what am doing:

      void _sayHi() async {
        _token = await _prefs.getToken();
        _userAddr = await _prefs.getUserAddr();
        var hi = getHiMsg(_token, _userAddr);
          print(hi);
          channel.sink.add(hi);
      }
    

    channel is just IOWebSocketChannel.connect(wsUrl) Here my server just can not get the right JSON format request, actually this is the right logic in Python:

    def hi_msg(token, addr):
    # change this to one account token and user_addr
    msg = {
        "token": token,
        "user_addr": addr,
        "ua": "py/macos",
        "device": "mac",
        "location": "Hunan"
    }
    out_msg = {
        "msg_type": "hi",
        "payload": msg
    }
    msg_str = json.dumps(out_msg)
    b = bytes(msg_str, 'utf-8')
    return b
    

    How to achieve this in Dart and Flutter? I am not quite familiar with Dart bytes operation.

    • Günter Zöchbauer
      Günter Zöchbauer almost 6 years
      What part is the problem?
    • Nicholas Jela
      Nicholas Jela almost 6 years
      @GünterZöchbauer I am just wonder how to encode json to bytes and send to my websocket server, as the same operation in Python codes.