Sample code for 30+ languages & platforms
React Native

Socket Send and Receive BinData

Demonstrates the Chilkat Socket ReceiveBdN and SendBd methods.

Chilkat React Native Downloads

React Native
import { BinData, Socket } from '@chilkat/react-native'

async function chilkatExample() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const sock = new Socket();

  // --------------------------------------------------------------------
  // This example uses the public TCP echo service at https://tcpbin.com/
  // --------------------------------------------------------------------

  const useTls = false;
  const port = 4242;
  const maxWaitMs = 5000;
  try {
    await sock.connectAsync('tcpbin.com', port, useTls, maxWaitMs);
  } catch {
    console.log(sock.lastErrorText);
    return;
  }

  // Wait a max of 2 seconds for a response..
  sock.maxReadIdleMs = 2000;

  // Send 26 bytes contained in a Chilkat BinData
  const bdToSend = new BinData();
  let i = 0;
  let byteVal = 65;
  while (i < 26) {
    bdToSend.appendByte(byteVal);
    byteVal++;
    i++;
  }

  // Send the contents of the BinData
  // Pass zero's in the 2nd and 3rd arguments to send the entire contents of the BinData.
  await sock.sendBdAsync(bdToSend, 0, 0);

  // The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
  await sock.sendByteAsync(10);

  // The echo server will echo back whatever is sent to it.
  // We should be able to read the same bytes back..
  const bdRecv = new BinData();
  // Receive the 26 bytes previously sent, plus the LF char.
  try {
    await sock.receiveBdNAsync(27, bdRecv);
  } catch {
    console.log(sock.lastErrorText);
    return;
  }

  // Show the contents of bdRecv in hex format
  console.log(bdRecv.getEncoded('hex'));

  // Output:  4142434445464748494A4B4C4D4E4F505152535455565758595A0A
}