@devioarts/capacitor-tcpclient

中文文档
0.2.1发布于 2026/07/08MITTypeScriptESM + CJS零依赖近 30 天下载 2021

TCP Client for Capacitor working on Android, iOS and Electron

原始使用文档
文档目录13 节
  1. Features
  2. Install
  3. Quick Start
  4. Capacitor App Example
  5. Documentation
  6. Platform Support
  7. Common Commands
  8. API
  9. createConnection(...)
  10. getPluginPlatform()
  11. Interfaces
  12. Type Aliases
  13. License

@devioarts/capacitor-tcpclient

TCP client plugin for Capacitor apps with native Android, iOS and Electron support.

Use it when your app needs to talk to a TCP device or service directly, for example printers, scanners, controllers, gateways or local network hardware.

Features

  • Native TCP sockets on Android, iOS and Electron
  • Multi-connection API with isolated listeners per connection
  • Raw writes, continuous stream reads and request/response reads
  • Byte payloads as number[] or Uint8Array
  • Optional expect pattern matching for protocol replies
  • Web stub for browser development builds

Install

npm install @devioarts/capacitor-tcpclient
npx cap sync

Android network permissions are merged automatically from the plugin manifest. See Getting started for manual Android fallback notes and the required iOS setup.

Quick Start

import { TCPClient } from '@devioarts/capacitor-tcpclient';

const conn = TCPClient.createConnection({
  host: '192.168.1.100',
  port: 9100,
  timeout: 3000,
});

await conn.connect();

const reply = await conn.writeAndRead({
  data: [0x1b, 0x40],
  timeout: 1000,
  maxBytes: 4096,
});

if (reply.error) {
  console.error(reply.errorMessage);
} else {
  console.log('Received bytes:', reply.data);
}

await conn.destroy();

Capacitor App Example

import { TCPClient, type TCPConnection } from '@devioarts/capacitor-tcpclient';

let connection: TCPConnection | undefined;

export async function connectToDevice(host: string) {
  connection = TCPClient.createConnection({ connectionId: 'main-device', host, port: 9100 });

  await connection.addListener('tcpDisconnect', ({ reason, error }) => {
    console.log('TCP disconnected:', reason, error ?? '');
  });

  return connection.connect();
}

export async function sendCommand(command: Uint8Array) {
  if (!connection) throw new Error('TCP connection is not ready');

  return connection.writeAndRead({
    data: command,
    expect: '0d0a',
    timeout: 1500,
    maxBytes: 8192,
  });
}

export async function disconnectFromDevice() {
  await connection?.destroy();
  connection = undefined;
}

Documentation

Platform Support

PlatformStatusNotes
AndroidNative TCPInternet/network permissions are merged automatically
iOSNative TCPRequires local network usage description for local devices
ElectronNative TCPUse Capacitor Electron or the manual bridge
WebDevelopment stubKeeps the same API shape, but does not open real TCP sockets

Common Commands

npm run build
npm test
npm run verify:web

API

The generated API below documents the root @devioarts/capacitor-tcpclient entry point used by Capacitor apps. The manual Electron bridge exposes the native methods directly over IPC, so it uses connectionId on every call instead of createConnection().

createConnection(...)

createConnection(options?: TcpCreateConnectionOptions | undefined) => TCPConnection

Create (or retrieve) a TCP connection instance.

  • Without connectionId: always creates a new instance with a generated UUID.
  • With connectionId: returns the existing instance if one was already created, otherwise creates a new one.
  • host/port/timeout/noDelay/keepAlive supplied here become defaults for connect().
ParamType
optionsTcpCreateConnectionOptions

Returns: TCPConnection


getPluginPlatform()

getPluginPlatform() => Promise<TcpGetPlatformResult>

Returns the platform identifier for this plugin's native implementation ('ios' | 'android' | 'electron' | 'web').

Distinct from the Capacitor core Capacitor.getPlatform() — use this when you need to know whether the TCP layer is backed by iOS, Android, Electron, or the browser development stub.

Returns: Promise<TcpGetPlatformResult>


Interfaces

TCPConnection

A single TCP connection instance returned by TCPClient.createConnection(). Each instance has its own socket, event listeners, and lifecycle.

PropType
connectionIdstring
MethodSignatureDescription
connect(options?: Partial<TcpConnectOptions> | undefined) => Promise<TcpConnectResult>Open the socket. Options are merged with the defaults supplied in createConnection(). host must be present either in createConnection() or here.
disconnect() => Promise<TcpDisconnectResult>Close the socket. Idempotent. Resolves after native teardown completes. Emits tcpDisconnect(reason: manual).
isConnected() => Promise<TcpIsConnectedResult>
isReading() => Promise<TcpIsReadingResult>
write(options: TcpWriteOptions) => Promise<TcpWriteResult>
writeAndRead(options: TcpWriteAndReadOptions) => Promise<TcpWriteAndReadResult>
startRead(options?: TcpStartReadOptions | undefined) => Promise<TcpStartStopResult>
stopRead() => Promise<TcpStartStopResult>
setReadTimeout(options: { readTimeout: number; }) => Promise<{ error: boolean; errorMessage?: string | null; }>Configure stream read timeout. - Android: sets SO_TIMEOUT on the continuous reader socket (applies during startRead). - iOS: no-op (evented I/O, no blocking timeout). - Electron: sets the default timeout value used by writeAndRead when no explicit timeout is passed; if called before connect, the default is stored without creating a socket state entry.
addListener(eventName: 'tcpData', listenerFunc: (event: TcpDataEvent) => void) => Promise<PluginListenerHandle>Subscribe to stream data. Only events for this connectionId are delivered.
addListener(eventName: 'tcpDisconnect', listenerFunc: (event: TcpDisconnectEvent) => void) => Promise<PluginListenerHandle>Subscribe to disconnect notifications for this connection.
removeAllListeners() => Promise<void>Remove all listeners registered through this instance.
destroy() => Promise<void>Disconnect, remove all listeners, and release this instance from the registry even if listener cleanup fails.

TcpConnectResult

PropType
errorboolean
errorMessagestring | null
connectedboolean

TcpConnectOptions

PropTypeDescription
hoststringHostname or IP address. Required (either here or in createConnection).
portnumberTCP port, default 9100. Valid range 1..65535.
timeoutnumberConnect timeout in milliseconds, default 3000. Includes DNS and socket connect budget.
noDelaybooleanEnable TCP_NODELAY (Nagle off). Default true.
keepAlivebooleanEnable SO_KEEPALIVE. Default true.

TcpDisconnectResult

PropType
errorboolean
errorMessagestring | null
disconnectedboolean
readingboolean

TcpIsConnectedResult

PropType
errorboolean
errorMessagestring | null
connectedboolean

TcpIsReadingResult

PropType
errorboolean
errorMessagestring | null
readingboolean

TcpWriteResult

PropType
errorboolean
errorMessagestring | null
bytesSentnumber

TcpWriteOptions

PropType
dataTcpBytePayload

TcpByteArrayLike

Byte-like array accepted by write APIs. Uint8Array is supported because it has numeric indexes and a length.

PropType
lengthnumber

TcpWriteAndReadResult

PropType
errorboolean
errorMessagestring | null
bytesSentnumber
bytesReceivednumber
datanumber[]
matchedboolean

TcpWriteAndReadOptions

PropTypeDescription
dataTcpBytePayload
timeoutnumberRR timeout in ms. Default 1000. Values <= 0 fall back to the default.
maxBytesnumberMaximum bytes to accumulate. Default 4096, capped at 16 MiB.
expectstring | TcpBytePayloadOptional pattern — reading stops when found. Accepts number[] / Uint8Array or hex string (e.g. "1B40", "0x1b 0x40"). Empty values are treated as no expect pattern.
suspendStreamDuringRRbooleanSuspend stream reader during RR to avoid consuming reply. Default true.

TcpStartStopResult

PropType
errorboolean
errorMessagestring | null
readingboolean

TcpStartReadOptions

PropTypeDescription
chunkSizenumberStream read chunk size in bytes. Default 4096, capped at 16 MiB. - Android/iOS: size of each native socket read before bridge micro-batching. - Electron: maximum bytes per emitted tcpData event after micro-batching.
readTimeoutnumberStream read timeout in ms. - Android: sets SO_TIMEOUT for the continuous reader. - iOS: no-op. - Electron: updates the per-connection default writeAndRead timeout; the stream reader itself remains event-driven.

PluginListenerHandle

PropType
remove() => Promise<void>

TcpDataEvent

Emitted by the stream reader. connectionId identifies which connection sent the data.

PropType
connectionIdstring
datanumber[]

TcpDisconnectEvent

Emitted when a connection closes.

PropType
connectionIdstring
disconnectedtrue
readingboolean
reason'error' | 'manual' | 'remote'
errorstring

TcpCreateConnectionOptions

Options for TCPClient.createConnection(). All fields are optional. host/port and other connect options set here become defaults for every connect() call on the returned instance.

PropTypeDescription
connectionIdstringOptional stable identifier for this connection. If an instance with this id already exists in the registry, it is returned as-is. Omit to get a new instance with a generated UUID each time.

TcpGetPlatformResult

PropType
errorboolean
errorMessagestring | null
platformTcpPlatform

Type Aliases

Partial

Make all properties in T optional

{ [P in keyof T]?: T[P]; }

TcpBytePayload

Byte payload accepted by write APIs. Values must be integer bytes in the 0..255 range.

number[] | TcpByteArrayLike

TcpPlatform

'ios' | 'android' | 'web' | 'electron'

License

MIT

版本与发布记录

@devioarts/capacitor-tcpclient 共发布 7 个版本,首次发布于 2025/08/31;过去 12 个月发布了 4 个版本。

版本发布日期距今
0.2.1latest2026/07/084 个月前
0.2.02026/07/074 个月前
0.1.02026/06/194 个月前
0.0.42026/06/105 个月前
0.0.32025/09/021.2 年前
0.0.22025/08/311.2 年前

关于 @devioarts/capacitor-tcpclient 的常见问题

@devioarts/capacitor-tcpclient 是什么?

TCP Client for Capacitor working on Android, iOS and Electron

如何安装 @devioarts/capacitor-tcpclient?

在项目目录运行 npm install @devioarts/capacitor-tcpclient,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@devioarts/capacitor-tcpclient 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@devioarts/capacitor-tcpclient 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@devioarts/capacitor-tcpclient 可以商用吗?

@devioarts/capacitor-tcpclient 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@devioarts/capacitor-tcpclient 的下载量有多少?

根据 npm 官方下载统计,@devioarts/capacitor-tcpclient 在 2026/10/12 – 2026/11/10 这 30 天内被下载 2,021 次,日均约 67 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@devioarts/capacitor-tcpclient 还在维护吗?

最新版本 0.2.1 发布于 2026/07/08(4 个月前);至今共发布 7 个版本,其中过去 12 个月发布了 4 个;首次发布于 2025/08/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。