Flutter 使用Socket创建TCP客户端

在Flutter中,可以使用dart:io库来进行Socket编程,从而实现TCP传输。

  1、与pc端建立连接


  Socket? socket;
  
  Future tcpConnect() async {
    socket = await Socket.connect(ip, port);
    print("连接成功");
    // 监听返回的数据信息
    socket!.listen((event) {
      print('接收到数据:event=$event');
      // 向服务端发送数据
      socket?.add(utf8.encode('Hello, Server!'));
      // 保证数据发送成功
      await socket?.flush();
    });
  }

2、向PC端发送数据帧


  Future tcpSend() async {
    // frameLength是数据帧长度
    Uint16List bytes = Uint16List(frameLength);
    // 发送数据帧
    try{
        socket?.add(bytes);
        await socket?.flush();
    }catch(e){
        print(e);
    }
  }

3、关闭连接

  // 关闭连接
  Future tcpClose() async {
    socket?.close();
    // socket?.destroy();
    print("关闭连接");
  }

4、可能涉及到的数据类型转换代码,可参考

  /// 字符串转ascii码
  List stringToAscii(String input) {
    return input.runes.map((rune) {
      return rune & 0xFF; // 使用0xFF确保我们只取低8位,即ASCII码
    }).toList();
  }

  /// ascii码转字符串
  String asciiToString(List asciiCodes) {
    return String.fromCharCodes(asciiCodes);
  }

  /// string 转 Uint16List
  Uint16List stringToUint16List(String input) {
    return Uint16List.fromList(input.codeUnits);
  }

  /// 计算异或值
  int calculateXorValue(List bytes) {
    // 计算异或值
    int xorValue = 0;
    for (var byte in bytes) {
      xorValue ^= byte;
    }
    return xorValue;
  }

你可能感兴趣的:(Flutter,flutter,tcp/ip)