React Native 创建 TCP 连接并发送和接收 HEX 数据 (react-native-tcp-socket)
import {Buffer} from 'buffer';
import TcpSocket from 'react-native-tcp-socket';

// 创建一个 TCP 连接
const client = TcpSocket.createConnection(options, () => {
    // 连接成功
    // 发送数据
    client.write('Hello server!'); // 发送 str
    client.write(new Buffer(data)); // 发送 str
    client.write(new Buffer(data, 'hex')); // 发送 hex
    
    // 关闭连接
    client.destroy();
});

// 接收到数据
client.on('data', function(data) {
    // 接收到的 data 是一个 buffer, js 里面的 buffer 是 10 进制 的数字
    // 转成 16 进制字符串 hex
    let hex = '';
    for (let i = 0; i < data.length; i++) {
        hex += data[i].toString(16);
    }
    console.log(hex);

    // 直接转成字符串(如果对方发来的不是字符串,直接这么转有可能乱码!)
    console.log(data.toString())
});

// 发生错误
client.on('error', function(error) {
    console.log(error);
});

// 连接关闭
client.on('close', function(){
    console.log('Connection closed!');
});

2831
0
3年前