Sample code for 30+ languages & platforms
React Native

TCP Socket Send Byte and Receive Byte

Demonstrates the Chilkat Socket ReceiveByte and SendByte 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;
  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 a byte.
  await sock.sendByteAsync(96);

  // 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 byte back..
  // After successfully reading, the byte value is available in the ReceivedInt property.
  const treatAsUnsignedInt = true;
  try {
    await sock.receiveByteAsync(treatAsUnsignedInt);
  } catch {
    console.log(sock.lastErrorText);
    return;
  }

  // Let's look at the value of the byte received.  It should be 96.
  console.log(sock.receivedInt);

  // The echo server also echoed the LF back.
  await sock.receiveByteAsync(treatAsUnsignedInt);
  // Assuming success..

  // Should be decimal 10.
  console.log(sock.receivedInt);
}