Sample code for 30+ languages & platforms
React Native

Socket Receive String Until Specific Byte Value is Received

Demonstrates the Chilkat Socket ReceiveStringUntilByte method.

Chilkat React Native Downloads

React Native
import { 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;
  let 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 some strings, each terminated by a 0 byte.
  await sock.sendStringAsync('This is the 1st string');
  await sock.sendByteAsync(0);
  await sock.sendStringAsync('This is string number 2');
  await sock.sendByteAsync(0);

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

  // Now let's receive what is echoed back....
  // Receive each string and the NULL byte.
  // The call to ReceiveStringUntilByte will receive incoming data until the lookForByte is encountered.
  // The lookForByte is receive and discarded (it is not returned in the string)
  const lookForByte = 0;
  let s1: string;
  try {
    s1 = await sock.receiveStringUntilByteAsync(lookForByte);
  } catch {
    console.log(sock.lastErrorText);
    return;
  }

  console.log(s1);

  let s2: string;
  try {
    s2 = await sock.receiveStringUntilByteAsync(lookForByte);
  } catch {
    console.log(sock.lastErrorText);
    return;
  }

  console.log(s2);

  // The echo server will also echo back the final LF
  await sock.receiveByteAsync(true);
  maxWaitMs = 100;
  await sock.closeAsync(100);

  // Output:
  // This is the 1st string
  // This is string number 2
}