You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

capacitor-tcp-socket

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

capacitor-tcp-socket

A TCP Socket Plugin for capacitor

7.1.0
latest
Source
npmnpm
Version published
Weekly downloads
120
380%
Maintainers
1
Weekly downloads
 
Created
Source

capacitor-tcp-socket

A TCP Socket Plugin for Capacitor, providing TCP communication capabilities in mobile applications.

Thanks to @ottimis

Installation

npm install capacitor-tcp-socket
npx cap sync

Basic Usage

import { TcpSocket } from 'capacitor-tcp-socket';

// Connect to TCP server
const connect = async () => {
  try {
    const result = await TcpSocket.connect({
      ipAddress: '192.168.1.100',
      port: 9100
    });
    console.log(`Connected with client ID: ${result.client}`);
    return result.client;
  } catch (error) {
    console.error('Connection failed:', error);
  }
};

// Send data
const sendData = async (clientId: number) => {
  try {
    await TcpSocket.send({
      client: clientId,
      data: 'Hello, TCP Server!'
    });
    console.log('Data sent successfully');
  } catch (error) {
    console.error('Send failed:', error);
  }
};

// Read data
const readData = async (clientId: number) => {
  try {
    const result = await TcpSocket.read({
      client: clientId,
      expectLen: 1024,  // Expected maximum bytes to read
      timeout: 10       // Timeout in seconds, iOS only
    });
    console.log('Received data:', result.result);
    return result.result;
  } catch (error) {
    console.error('Read failed:', error);
  }
};

// Disconnect
const disconnect = async (clientId: number) => {
  try {
    const result = await TcpSocket.disconnect({
      client: clientId
    });
    console.log(`Disconnected client: ${result.client}`);
  } catch (error) {
    console.error('Disconnect failed:', error);
  }
};

// Usage example
const main = async () => {
  const clientId = await connect();
  if (clientId !== undefined) {
    await sendData(clientId);
    const data = await readData(clientId);
    await disconnect(clientId);
  }
};

Working with Different Encodings

This plugin supports multiple data encodings for handling various types of data:

Using UTF-8 Encoding (Default)

import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket';

// Send text data using UTF-8 encoding
await TcpSocket.send({
  client: clientId,
  data: 'Hello, World!',
  encoding: DataEncoding.UTF8 // Optional, UTF8 is the default
});

// Read data as UTF-8 text
const result = await TcpSocket.read({
  client: clientId,
  expectLen: 1024,
  encoding: DataEncoding.UTF8 // Optional, UTF8 is the default
});

console.log('Received text:', result.result);
console.log('Received encoding:', result.encoding);

Using Base64 Encoding for Binary Data

import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket';

// Send binary data using Base64 encoding
const binaryData = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // "Hello" in ASCII
const base64Data = btoa(String.fromCharCode.apply(null, binaryData));

await TcpSocket.send({
  client: clientId,
  data: base64Data,
  encoding: DataEncoding.BASE64
});

// Read binary data as Base64
const result = await TcpSocket.read({
  client: clientId,
  expectLen: 1024,
  encoding: DataEncoding.BASE64
});

// Convert Base64 back to binary if needed
const binaryResult = new Uint8Array(
  atob(result.result)
    .split('')
    .map(c => c.charCodeAt(0))
);

Using Hexadecimal Encoding

import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket';

// Send data using hex encoding
const hexData = "48656C6C6F"; // "Hello" in hex

await TcpSocket.send({
  client: clientId,
  data: hexData,
  encoding: DataEncoding.HEX
});

// Read data as hex string
const result = await TcpSocket.read({
  client: clientId,
  expectLen: 1024,
  encoding: DataEncoding.HEX
});

console.log('Received hex data:', result.result);
// Example output: "48656C6C6F"

// Convert hex to binary if needed
function hexToBytes(hex) {
  const bytes = [];
  for (let c = 0; c < hex.length; c += 2) {
    bytes.push(parseInt(hex.substr(c, 2), 16));
  }
  return new Uint8Array(bytes);
}

const binaryFromHex = hexToBytes(result.result);

Platform-Specific Considerations

Web

  • Not supported on the web platform.

iOS

  • iOS implementation uses the SwiftSocket library for TCP functionality.
  • Supports setting a timeout for read operations (via the timeout parameter).

Android

  • Android implementation uses the standard Java Socket API.
  • Currently, the read timeout parameter is not supported on Android.

Example Project

Check out the example directory to see a complete sample application.

Running the example app:

cd example
npm install
npm start

API

TCP Socket Plugin interface for Capacitor Provides methods for TCP socket communication

connect(...)

connect(options: ConnectOptions) => Promise<ConnectResult>

Connects to a TCP server

ParamTypeDescription
optionsConnectOptionsConnection options including IP address and port

Returns: Promise<ConnectResult>

send(...)

send(options: SendOptions) => Promise<void>

Sends data to a connected TCP server

ParamTypeDescription
optionsSendOptionsSend options including client ID, data and encoding

read(...)

read(options: ReadOptions) => Promise<ReadResult>

Reads data from a connected TCP server

ParamTypeDescription
optionsReadOptionsRead options including client ID, expected length and timeout

Returns: Promise<ReadResult>

disconnect(...)

disconnect(options: DisconnectOptions) => Promise<DisconnectResult>

Disconnects from a TCP server

ParamTypeDescription
optionsDisconnectOptionsDisconnect options with client ID

Returns: Promise<DisconnectResult>

Interfaces

ConnectResult

Result of a successful connection

PropTypeDescription
clientnumberClient ID that can be used for subsequent operations

ConnectOptions

Options for connecting to a TCP server

PropTypeDescriptionDefault
ipAddressstringIP address of the server to connect to
portnumberPort number of the TCP server9100

SendOptions

Options for sending data to a TCP server

PropTypeDescriptionDefault
clientnumberClient ID from a previous connect call
datastringData string to send to the server
encodingDataEncodingEncoding type for the dataDataEncoding.UTF8

ReadResult

Result of a read operation

PropTypeDescription
resultstringData read from the server Can be UTF-8 string, Base64 encoded string, or Hex string depending on the encoding option
encodingDataEncodingThe encoding of the returned result

ReadOptions

Options for reading data from a TCP server

PropTypeDescriptionDefault
clientnumberClient ID from a previous connect call
expectLennumberExpected number of bytes to read
timeoutnumberRead timeout in seconds10
encodingDataEncodingPreferred encoding for returned dataDataEncoding.UTF8

DisconnectResult

Result of a disconnect operation

PropTypeDescription
clientnumberClient ID that was disconnected

DisconnectOptions

Options for disconnecting from a TCP server

PropTypeDescription
clientnumberClient ID from a previous connect call

Enums

DataEncoding

MembersValueDescription
UTF8'utf8'UTF-8 text encoding
BASE64'base64'Base64 encoded data
HEX'hex'Hexadecimal string

Keywords

capacitor

FAQs

Package last updated on 21 Apr 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts