### Install and Run Example Project Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/README.md Navigate to the example directory, install dependencies, and start the example application. ```bash cd example npm install npm start ``` -------------------------------- ### Run Example with npm start Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/example/README.md Use this command to run the provided example. Ensure you have npm installed. ```bash npm start ``` -------------------------------- ### Install capacitor-tcp-socket Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/README.md Install the plugin using npm and sync with Capacitor. ```bash npm install capacitor-tcp-socket npx cap sync ``` -------------------------------- ### Install Dependencies Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/CONTRIBUTING.md Installs project dependencies using npm. Run this after cloning the repository. ```shell npm install ``` -------------------------------- ### Install and Import Capacitor TCP Socket Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Instructions for installing the plugin via npm and importing necessary components into your project. ```bash npm install capacitor-tcp-socket && npx cap sync ``` ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket' ``` -------------------------------- ### Install SwiftLint Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/CONTRIBUTING.md Installs SwiftLint using Homebrew for macOS users. This tool helps enforce Swift code style and quality. ```shell brew install swiftlint ``` -------------------------------- ### Connect to a TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Example of establishing a TCP connection to a specified IP address and port using the TcpSocket plugin. ```typescript const result = await TcpSocket.connect({ ipAddress, port }) ``` -------------------------------- ### SendOptions Example Usage Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Shows how to construct and use the SendOptions object with TcpSocket.send() for transmitting data over a TCP connection. ```typescript const sendOptions: SendOptions = { client: 0, data: 'Hello World', encoding: DataEncoding.UTF8 }; await TcpSocket.send(sendOptions); ``` -------------------------------- ### Per-Call Configuration Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Demonstrates establishing two independent TCP connections with different IP addresses and ports. Each connection is configured individually at the time of the 'connect' call. ```typescript const client1 = await TcpSocket.connect({ ipAddress: '10.0.0.1', port: 9100 }); const client2 = await TcpSocket.connect({ ipAddress: '192.168.1.1', port: 5000 // Different port }); // Each connection uses its own settings await TcpSocket.send({ client: client1.client, data: 'data1' }); await TcpSocket.send({ client: client2.client, data: 'data2' }); ``` -------------------------------- ### Complete Robust TCP Communication Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/errors.md A comprehensive example demonstrating error handling for connection, sending, and reading data, including timeout handling and ensuring disconnection. ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket'; async function robustTcpCommunication() { let clientId: number | null = null; try { // Step 1: Connect with error handling try { const result = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); clientId = result.client; console.log('Connected:', clientId); } catch (connectError) { console.error('Failed to connect:', connectError.message); return false; } // Step 2: Send with error handling try { await TcpSocket.send({ client: clientId!, data: 'REQUEST', encoding: DataEncoding.UTF8 }); } catch (sendError) { console.error('Failed to send:', sendError.message); throw sendError; } // Step 3: Read with timeout handling try { const result = await TcpSocket.read({ client: clientId!, expectLen: 1024, timeout: 5 }); if (result.result === '') { console.log('No data received within timeout'); } else { console.log('Received:', result.result); } } catch (readError) { if (readError.code === 'EOF') { console.error('Server closed connection'); } else { console.error('Read error:', readError.message); } throw readError; } return true; } finally { // Always disconnect if (clientId !== null) { try { await TcpSocket.disconnect({ client: clientId }); console.log('Disconnected'); } catch (disconnectError) { console.error('Disconnect error:', disconnectError.message); } } } } ``` -------------------------------- ### TCP Socket Communication Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Demonstrates establishing a TCP connection, sending data, reading a response, and disconnecting using the TcpSocket plugin. ```typescript // Connect const result = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); const clientId = result.client; // Send await TcpSocket.send({ client: clientId, data: 'Hello, TCP Server!', encoding: DataEncoding.UTF8 }); // Read const response = await TcpSocket.read({ client: clientId, expectLen: 1024, timeout: 10, encoding: DataEncoding.UTF8 }); // Disconnect await TcpSocket.disconnect({ client: clientId }); ``` -------------------------------- ### ConnectResult Example Usage Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Demonstrates how to use the TcpSocket.connect() method and access the client ID from the returned ConnectResult. ```typescript const result = await TcpSocket.connect({ ipAddress: '192.168.1.1' }); const clientId: number = result.client; ``` -------------------------------- ### Implementing TCP Socket Connection Pooling Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md A connection pool manages a set of reusable TCP client connections. This example demonstrates how to get a connection from the pool, create a new one if the pool is empty, return a connection to the pool, and close all connections. ```typescript class ConnectionPool { private pool: number[] = []; private ip: string; private port: number; constructor(ip: string, port: number) { this.ip = ip; this.port = port; } async getConnection(): Promise { if (this.pool.length > 0) { return this.pool.pop()!; } const result = await TcpSocket.connect({ ipAddress: this.ip, port: this.port }); return result.client; } returnConnection(clientId: number) { // In production, validate connection is still active this.pool.push(clientId); } async closeAll() { for (const clientId of this.pool) { try { await TcpSocket.disconnect({ client: clientId }); } catch (error) { console.error('Error closing connection:', error); } } this.pool = []; } } ``` -------------------------------- ### Send Binary Data as Hex Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md This example demonstrates sending binary data represented as a hexadecimal string. This is useful for low-level protocol communication. ```typescript await TcpSocket.send({ client: 0, data: '1B402048656C6C6F', // ESC @ H "Hello" encoding: DataEncoding.HEX }); ``` -------------------------------- ### Example Disconnect Call Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Call the disconnect method with the required DisconnectOptions. This initiates the disconnection process for the specified client. ```typescript const disconnectOptions: DisconnectOptions = { client: 0 }; await TcpSocket.disconnect(disconnectOptions); ``` -------------------------------- ### Complete TCP Socket Workflow Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/tcp-socket.md Demonstrates the full lifecycle of a TCP socket connection: connecting to a server, sending data, reading a response, and disconnecting. Ensure the server IP and port are correct for your environment. The `client` ID is returned upon successful connection and must be used for subsequent operations. ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket'; async function communicateWithServer() { try { // Step 1: Connect to the server const connectResult = await TcpSocket.connect({ ipAddress: '10.0.0.1', port: 5000 }); const clientId = connectResult.client; console.log('Connected with client ID:', clientId); // Step 2: Send some data await TcpSocket.send({ client: clientId, data: 'REQUEST_DATA', encoding: DataEncoding.UTF8 }); console.log('Request sent'); // Step 3: Read the response const readResult = await TcpSocket.read({ client: clientId, expectLen: 2048, timeout: 15, encoding: DataEncoding.UTF8 }); console.log('Received:', readResult.result); // Step 4: Disconnect await TcpSocket.disconnect({ client: clientId }); console.log('Disconnected'); } catch (error) { console.error('Communication failed:', error); } } ``` -------------------------------- ### Receive Data as Hexadecimal Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Example of receiving data and interpreting it as a hexadecimal string. Includes a helper function to convert the hex string back to binary bytes. ```typescript // Receive as hex const result = await TcpSocket.read({ client: 0, expectLen: 256, encoding: DataEncoding.HEX }); // result.result is hex string like "1b4020aa55ff00" // Convert to bytes function hexToBinary(hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2); for (let i = 0; i < hex.length; i += 2) { bytes[i / 2] = parseInt(hex.substr(i, 2), 16); } return bytes; } const binaryData = hexToBinary(result.result); // Or work with it directly as hex console.log('First byte:', parseInt(result.result.substr(0, 2), 16)); // 0x1B ``` -------------------------------- ### Base64 Encoding for Large Binary Data Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Demonstrates the recommended Base64 encoding for large binary transfers, highlighting its efficiency over Hex and safety over UTF-8. It also shows an inefficient Hex encoding example for comparison. ```typescript // For large binary transfers, use Base64 // It's more efficient than hex and safer than UTF-8 const largeData = new Uint8Array(1024 * 1024); // 1MB const base64 = btoa(String.fromCharCode(...largeData)); // Don't use hex for large data - creates 2MB string const hex = largeData .map(b => b.toString(16).padStart(2, '0')) .join(''); // Very slow for large data ``` -------------------------------- ### Integration Test with Real TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md Set up a test TCP server using Node.js 'net' module and test the TcpSocket plugin's communication capabilities. Ensure the server is started before tests and closed after. ```typescript // Use a test TCP server import { createServer } from 'net'; const testServer = createServer((socket) => { socket.on('data', (data) => { socket.write(`Echo: ${data}`); }); }); beforeAll(() => testServer.listen(9999, '127.0.0.1')); afterAll(() => testServer.close()); // Test with real connection test('should communicate with server', async () => { const result = await TcpSocket.connect({ ipAddress: '127.0.0.1', port: 9999 }); const client = result.client; await TcpSocket.send({ client, data: 'test message' }); const response = await TcpSocket.read({ client, expectLen: 1024 }); expect(response.result).toContain('Echo:'); await TcpSocket.disconnect({ client }); }); ``` -------------------------------- ### Web Alternative: WebSocket Usage Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Provides an example of using the WebSocket API as an alternative to TCP sockets on the Web platform. This is the recommended approach for web environments. ```typescript // Instead of TCP on web, use WebSocket const ws = new WebSocket('ws://server:9100'); ws.onmessage = (event) => { console.log('Received:', event.data); }; ws.send('data'); ``` -------------------------------- ### Example Disconnect Result Handling Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Log the client identifier upon successful disconnection. The result object confirms which client was disconnected. ```typescript const result = await TcpSocket.disconnect({ client: 0 }); console.log('Disconnected client:', result.client); ``` -------------------------------- ### Send Data as Hexadecimal Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Examples of sending data using hexadecimal encoding. The input string can be plain hex, space-separated, or include '0x' prefixes, and formatting is automatically stripped. ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket'; // Send ESC/POS printer command (reset printer) // ESC = 0x1B, @ = 0x40 await TcpSocket.send({ client: 0, data: '1B40', // or "1B 40" or "0x1B 0x40" encoding: DataEncoding.HEX }); // Binary sent: 0x1B 0x40 // Send device register command await TcpSocket.send({ client: 0, data: 'A5 B2 FF 00', // Can use spaces for readability encoding: DataEncoding.HEX }); // Send protocol frame const frameData = [ 0x02, // STX 0x01, 0x02, 0x03, // Data payload 0x03 // ETX ]; const hex = frameData .map(b => b.toString(16).padStart(2, '0')) .join(''); await TcpSocket.send({ client: 0, data: hex, encoding: DataEncoding.HEX }); ``` -------------------------------- ### Send Protocol Buffer Data as Base64 Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Provides an example of sending serialized protocol buffer data as Base64. The binary data from protobuf serialization is converted to a string and then Base64 encoded. ```typescript // Protocol buffer to Base64 const protobufBytes = new Uint8Array([...]); // from protobuf serialization const base64Proto = btoa(String.fromCharCode(...protobufBytes)); await TcpSocket.send({ client: 0, data: base64Proto, encoding: DataEncoding.BASE64 }); ``` -------------------------------- ### BASE64 Encoding Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Use BASE64 encoding for transmitting binary data as text. On send, data must be valid Base64. On read, received bytes are Base64-encoded. This increases data size by approximately 33%. ```typescript // Send binary data as Base64 const binaryPayload = btoa('\x00\x01\x02\x03'); await TcpSocket.send({ client: 0, data: binaryPayload, encoding: DataEncoding.BASE64 }); ``` ```typescript // Receive binary data as Base64 const response = await TcpSocket.read({ client: 0, expectLen: 2048, encoding: DataEncoding.BASE64 }); // Decode: atob(response.result) to get original binary ``` -------------------------------- ### Connect TCP Client Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Demonstrates how to establish a TCP connection with a specified IP address and port, including timeout handling and success/failure resolution. ```swift let client = TCPClient(address: "192.168.1.100", port: 9100) switch client.connect(timeout: 10) { case .success: clients.append(client) // Return index to caller case .failure(let error): // Return error } ``` -------------------------------- ### connect() Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Establishes a TCP connection to a specified IP address and port. It reads connection details from the plugin call, creates a socket, and adds it to a client list. The operation resolves with the client index or rejects on failure. ```APIDOC ## connect() ### Description Establishes a TCP connection to a specified IP address and port. It reads connection details from the plugin call, creates a socket, and adds it to a client list. The operation resolves with the client index or rejects on failure. ### Method Signature ```java @PluginMethod public void connect(PluginCall call) ``` ### Parameters - `ipAddress` (string) - Required: The IP address to connect to. - `port` (number) - Optional: The port number to connect to. Defaults to 9100. ### Response - **Success**: Resolves with a `JSObject` containing `{"client": index}` where `index` is the identifier for the new client connection. - **Failure**: Rejects with an `IOException` message if the connection fails. ``` -------------------------------- ### ConnectOptions Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Configuration options for initiating a TCP connection. ```APIDOC ## ConnectOptions ### Description Configuration options for initiating a TCP connection. ### Fields - **ipAddress** (string) - Required - IP address of the TCP server to connect to. Can be an IPv4 address (e.g., "192.168.1.100") or domain name (if resolver is available). - **port** (number) - Optional - Default: 9100 - Port number of the TCP server. Must be a valid port number (1-65535). ``` -------------------------------- ### Disconnect from a TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Example of closing an active TCP connection using the TcpSocket plugin. ```typescript await TcpSocket.disconnect({ client }) ``` -------------------------------- ### Establish and Use Multiple TCP Connections Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Demonstrates how to establish two independent TCP connections and send data to each using their respective client IDs. Ensure the IP addresses are valid for your network. ```typescript const client1 = await TcpSocket.connect({ ipAddress: '10.0.0.1' }); const client2 = await TcpSocket.connect({ ipAddress: '10.0.0.2' }); // Use both independently await TcpSocket.send({ client: client1.client, data: 'cmd1' }); await TcpSocket.send({ client: client2.client, data: 'cmd2' }); ``` -------------------------------- ### connect() Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/tcp-socket.md Establishes a connection to a TCP server and returns a client identifier for subsequent operations. ```APIDOC ## connect() ### Description Establishes a connection to a TCP server and returns a client identifier for subsequent operations. ### Method connect ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (ConnectOptions) - Required - Configuration object for the connection - **ipAddress** (string) - Required - IP address of the TCP server to connect to - **port** (number) - Optional - Port number of the TCP server (default: 9100) ### Request Example ```typescript const clientId = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); console.log('Connected with client ID:', clientId.client); ``` ### Response #### Success Response (200) - **client** (number) - Client identifier for subsequent operations. #### Response Example ```json { "client": 0 } ``` ### Throws/Rejects - Connection failed (platform-specific error message) - On web: Always rejects with "TCP sockets are not supported in web browsers." ``` -------------------------------- ### Connect to TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Establishes a connection to a TCP server. Ensure the IP address and port are correct for your target device. ```typescript const client = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); ``` -------------------------------- ### Send UTF-8 Text (Explicit Encoding) Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md This example explicitly sets the encoding to UTF8 when sending text data. It is functionally equivalent to the default behavior. ```typescript await TcpSocket.send({ client: 0, data: 'Print this text', encoding: DataEncoding.UTF8 }); ``` -------------------------------- ### Connect to a TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Establishes a TCP connection to a specified IP address and port. Blocks until connection succeeds or fails. On failure, it rejects with an IOException message. ```java @PluginMethod public void connect(PluginCall call) { String ipAddress = call.getString("ipAddress"); Integer port = call.getInt("port", 9100); if (ipAddress == null) { call.reject("ipAddress is required"); return; } try { Socket socket = new Socket(ipAddress, port); clients.add(socket); call.resolve(new JSObject().put("client", clients.size() - 1)); } catch (IOException e) { call.reject(e.getMessage()); } } ``` -------------------------------- ### connect Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/README.md Connects to a TCP server with the provided connection options. ```APIDOC ## connect(...) ### Description Connects to a TCP server. ### Method connect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (ConnectOptions) - Required - Connection options including IP address and port ### Request Example ```json { "options": { "ip": "192.168.1.1", "port": 12345 } } ``` ### Response #### Success Response (200) - **ConnectResult** - Result of the connection attempt #### Response Example ```json { "result": { "success": true, "clientId": "some-client-id" } } ``` ``` -------------------------------- ### Encode Binary to Base64 and Send Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Demonstrates how to convert binary data (Uint8Array) to a Base64 string using `btoa` and send it over the TCP socket with the `DataEncoding.BASE64` option. Ensure the input is valid Base64. ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket'; // Encode binary to Base64 function binaryToBase64(bytes: Uint8Array): string { return btoa(String.fromCharCode(...bytes)); } const binaryData = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); const base64 = binaryToBase64(binaryData); // "SGVsbG8=" // Send as Base64 await TcpSocket.send({ client: 0, data: base64, encoding: DataEncoding.BASE64 }); // Binary sent: 48 65 6C 6C 6F (the word "Hello") ``` -------------------------------- ### Disconnect TCP Client Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Provides an example of closing an active TCP connection using a client index. Note that the client is not removed from the internal array upon disconnection. ```swift // Example of disconnecting a client (actual implementation would involve call parameters) // let clientIndex = 0; // client.close() ``` -------------------------------- ### Read Data with Timeout Handling Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/tcp-socket.md Reads data from a TCP socket with a specified timeout. This example demonstrates how to handle cases where no data is received within the timeout period or when the server closes the connection. ```typescript try { const result = await TcpSocket.read({ client: clientId, expectLen: 512, timeout: 5 // 5 second timeout }); if (result.result === '') { console.log('No data received within timeout period'); } else { console.log('Data:', result.result); } } catch (error) { if (error.code === 'EOF') { console.log('Server closed the connection'); } } ``` -------------------------------- ### Web Implementation: connect() Method Stub Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md The `connect` method in the web implementation logs the attempt and rejects the promise, as TCP sockets are not supported in web browsers. ```typescript connect(options: ConnectOptions): Promise { console.log('TCP connection attempted in web context:', options) return Promise.reject(new Error(this.ERROR_MESSAGE)) } ``` -------------------------------- ### Receive Binary Data as Base64 Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Demonstrates how to receive binary data from the server, encoded as Base64. The received Base64 string is then decoded back into a Uint8Array using `atob`. ```typescript // Receive binary data as Base64 const result = await TcpSocket.read({ client: 0, expectLen: 2048, encoding: DataEncoding.BASE64 }); // result.result contains Base64 string // Decode Base64 back to binary function base64ToBinary(base64: string): Uint8Array { const binaryString = atob(base64); return new Uint8Array(binaryString.split('').map(c => c.charCodeAt(0))); } const binaryData = base64ToBinary(result.result); ``` -------------------------------- ### UTF8 Encoding Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Use UTF8 encoding for text-based protocols. On send, data is encoded to UTF-8 bytes. On read, bytes are decoded to UTF-8 string, falling back to Base64 on failure. This is the default encoding. ```typescript // Send text command await TcpSocket.send({ client: 0, data: 'STATUS\r\n', encoding: DataEncoding.UTF8 }); ``` ```typescript // Receive text response const response = await TcpSocket.read({ client: 0, expectLen: 1024, encoding: DataEncoding.UTF8 }); console.log('Response:', response.result); ``` -------------------------------- ### Binary to Base64 to Binary Conversion Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Shows how to convert binary data to a Base64 string for transmission and then decode it back into binary upon reception. Uses `btoa` for encoding and `atob` for decoding. ```typescript // Start with binary const binaryData = new Uint8Array([0x48, 0x65, 0x6C, 0x6C, 0x6F]); // Convert to Base64 const base64 = btoa(String.fromCharCode(...binaryData)); // "SGVsbG8=" // Send as Base64 await TcpSocket.send({ client: 0, data: base64, encoding: DataEncoding.BASE64 }); // Receive and decode const response = await TcpSocket.read({ client: 0, expectLen: 1024, encoding: DataEncoding.BASE64 }); const receivedBinary = new Uint8Array( atob(response.result).split('').map(c => c.charCodeAt(0)) ); ``` -------------------------------- ### Connect to TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/README.md Use the connect method to establish a TCP connection. Requires connection options including IP address and port. ```typescript connect(options: ConnectOptions) => Promise ``` -------------------------------- ### HEX Encoding Example Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Use HEX encoding for low-level protocols or debugging. On send, data must be valid hex digits; formatting like '0x' prefixes and whitespace is stripped. On read, bytes are converted to lowercase hex digits. This doubles the data size compared to raw binary. ```typescript // Send hex-encoded binary await TcpSocket.send({ client: 0, data: '1B4020', // ESC @ SPACE in hex encoding: DataEncoding.HEX }); ``` ```typescript // Can include formatting (stripped before sending) await TcpSocket.send({ client: 0, data: '0x1B 0x40 0x20', // Same as above encoding: DataEncoding.HEX }); ``` ```typescript // Receive as hex const response = await TcpSocket.read({ client: 0, expectLen: 256, encoding: DataEncoding.HEX }); // response.result might be "48656c6c6f" (Hello in hex) ``` -------------------------------- ### Connect to a TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Establishes a new TCP connection to a specified IP address and port. Returns a unique client ID for subsequent operations. ```APIDOC ## connect ### Description Establishes a TCP connection to a server. ### Method POST ### Endpoint /connect ### Parameters #### Request Body - **ipAddress** (string) - Required - The IP address of the server. - **port** (number) - Optional - The port number of the server. Defaults to 9100. ### Request Example ```json { "ipAddress": "10.0.0.1", "port": 9100 } ``` ### Response #### Success Response (200) - **client** (number) - The unique identifier for the established connection. ``` -------------------------------- ### Common Hex Patterns for Device Communication Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Illustrates constructing and sending a device command with parameters and checksum using hexadecimal strings, and parsing a hexadecimal response. ```typescript // Device command with parameters const command = 'C0'; // Command byte const param1 = '42'; // Parameter 1 const param2 = 'FF'; // Parameter 2 const checksum = '01'; // Checksum const fullCommand = command + param1 + param2 + checksum; // "C042FF01" await TcpSocket.send({ client: 0, data: fullCommand, encoding: DataEncoding.HEX }); // Read response and parse const response = await TcpSocket.read({ client: 0, expectLen: 10, encoding: DataEncoding.HEX }); // Extract bytes const status = parseInt(response.result.substr(0, 2), 16); const value = parseInt(response.result.substr(2, 4), 16); ``` -------------------------------- ### Publish Plugin Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/CONTRIBUTING.md Publishes the plugin to npm. The `prepublishOnly` hook ensures the plugin is prepared before publishing. ```shell npm publish ``` -------------------------------- ### Multi-Connection Management with Client IDs Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Illustrates how to manage multiple simultaneous TCP connections using a Map to store client IDs. This allows for independent control and disconnection of each connection. ```typescript // Maintain a Map of connections const connections: Map = new Map(); // Connect to device 1 const d1 = await TcpSocket.connect({ ipAddress: '10.0.0.1' }); connections.set('device1', d1.client); // Connect to device 2 const d2 = await TcpSocket.connect({ ipAddress: '10.0.0.2' }); connections.set('device2', d2.client); // Use them independently await TcpSocket.send({ client: connections.get('device1')!, data: 'command1' }); await TcpSocket.send({ client: connections.get('device2')!, data: 'command2' }); // Disconnect all for (const clientId of connections.values()) { await TcpSocket.disconnect({ client: clientId }); } ``` -------------------------------- ### ReadOptions Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Configuration options for reading data from a TCP connection. ```APIDOC ## ReadOptions ### Description Configuration options for reading data from a TCP connection. ### Fields - **client** (number) - Required - Client identifier from a previous `connect()` call. Must be a valid client ID from an active connection. - **expectLen** (number) - Required - Maximum number of bytes to read from the server in a single operation. Acts as the buffer size; actual bytes read may be less. - **timeout** (number) - Optional - Read operation timeout in seconds. Defaults to 10. If no data arrives within this period, the operation returns an empty result (except Android which may throw EOF). - **encoding** (DataEncoding) - Optional - Preferred encoding for the returned data. Defaults to UTF8. The response will be encoded in this format; if UTF8 decoding fails, Base64 is used automatically. ### Example Usage ```typescript const readOptions: ReadOptions = { client: 0, expectLen: 1024, timeout: 10, encoding: DataEncoding.UTF8 }; const result = await TcpSocket.read(readOptions); ``` ``` -------------------------------- ### Data Size Comparison for Encodings Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Compares the resulting data size percentages for raw binary, UTF8, Hex, and Base64 encodings. Hex and Base64 have fixed size increases. ```plaintext Raw binary: 100% UTF8: 100-400% (ASCII is 100%, Unicode varies) Hex: 200% (fixed) Base64: 133% (fixed) ``` -------------------------------- ### TcpSocketPlugin Type Diagram Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Illustrates the relationships between TcpSocketPlugin methods, their options, and their results. Shows the structure of ConnectOptions, ConnectResult, SendOptions, ReadOptions, ReadResult, and DisconnectOptions. ```plaintext TcpSocketPlugin ├── connect(ConnectOptions) → ConnectResult │ └── ConnectResult { client: number } ├── send(SendOptions) → Promise │ └── SendOptions { client, data, encoding?: DataEncoding } ├── read(ReadOptions) → ReadResult │ ├── ReadOptions { client, expectLen, timeout?, encoding?: DataEncoding } │ └── ReadResult { result?: string, encoding?: DataEncoding } └── disconnect(DisconnectOptions) → DisconnectResult ├── DisconnectOptions { client: number } └── DisconnectResult { client: number } ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Demonstrates how to catch and differentiate between various connection-related errors, such as general connection failures or platform-specific issues like unsupported platforms. ```typescript try { const result = await TcpSocket.connect({ ipAddress: '...' }); } catch (error) { if (error.message.includes('Connection failed')) { // Connection error } else if (error.message === 'TCP sockets are not supported in web browsers.') { // Web platform } } ``` -------------------------------- ### Send Data with Different Encodings Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Demonstrates sending data using UTF8, Base64, and Hex encodings. Ensure data format matches the selected encoding. Base64 and Hex are suitable for binary data. ```typescript import { DataEncoding } from 'capacitor-tcp-socket'; // UTF-8 text await TcpSocket.send({ client, data: 'text', encoding: DataEncoding.UTF8 }); // Binary data as Base64 const base64 = 'SGVsbG8='; // "Hello" in Base64 await TcpSocket.send({ client, data: base64, encoding: DataEncoding.BASE64 }); // Binary data as Hex const hex = '48656C6C6F'; // "Hello" in hex await TcpSocket.send({ client, data: hex, encoding: DataEncoding.HEX }); ``` -------------------------------- ### Text to UTF-8 Binary and Back Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Demonstrates sending text data using UTF-8 encoding and receiving it back as text. Ensure the server is configured to handle UTF-8. ```typescript // Start with text const originalText = "Hello, 世界!"; // Method 1: UTF-8 round-trip await TcpSocket.send({ client: 0, data: originalText, encoding: DataEncoding.UTF8 }); const response = await TcpSocket.read({ client: 0, expectLen: 1024, encoding: DataEncoding.UTF8 }); console.log(response.result); // "Hello, 世界!" ``` -------------------------------- ### Typical Capacitor TCP Socket Usage Pattern Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md Demonstrates a complete connection lifecycle: connect, send data, read response, and disconnect. Always use try-finally for cleanup and store the client ID for subsequent operations. ```typescript async function communicateWithDevice() { let clientId: number | null = null; try { // 1. Connect const connectResult = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); clientId = connectResult.client; console.log('Connected:', clientId); // 2. Exchange data await TcpSocket.send({ client: clientId, data: 'COMMAND', encoding: DataEncoding.UTF8 }); const response = await TcpSocket.read({ client: clientId, expectLen: 1024, timeout: 10 }); console.log('Response:', response.result); // 3. Disconnect await TcpSocket.disconnect({ client: clientId }); } catch (error) { console.error('Error:', error); } finally { // Always attempt cleanup if (clientId !== null) { try { await TcpSocket.disconnect({ client: clientId }); } catch { // Ignore cleanup errors } } } } ``` -------------------------------- ### Connect to Generic Network Device Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md This pattern is suitable for connecting to generic network devices. It allows for configurable read timeouts, buffer sizes, and data encoding. Ensure the device's IP address and port are correctly specified. ```typescript const config = { ipAddress: '192.168.1.50', port: 5000, readTimeout: 10, maxBuffer: 2048, encoding: DataEncoding.UTF8 }; const client = await TcpSocket.connect({ ipAddress: config.ipAddress, port: config.port }); await TcpSocket.send({ client, data: 'QUERY', encoding: config.encoding }); const response = await TcpSocket.read({ client, expectLen: config.maxBuffer, timeout: config.readTimeout, encoding: config.encoding }); ``` -------------------------------- ### Connect to TCP Server Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/tcp-socket.md Establishes a connection to a TCP server using its IP address and port. Requires the client ID for subsequent operations. Rejects on web. ```typescript const clientId = await TcpSocket.connect({ ipAddress: '192.168.1.100', port: 9100 }); console.log('Connected with client ID:', clientId.client); ``` -------------------------------- ### ConnectOptions Interface Definition Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/types.md Specifies the configuration options required for initiating a TCP connection. Includes the IP address and an optional port number. ```typescript export interface ConnectOptions { ipAddress: string; port?: number; } ``` -------------------------------- ### Android Client Management Implementation Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Demonstrates the management of active socket connections on Android using an ArrayList of Socket objects. The client ID is derived from the zero-based index. ```java private List clients = new ArrayList<>() ``` -------------------------------- ### Web Implementation: read() Method Stub Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md The `read` method in the web implementation logs the attempt and rejects the promise, as TCP sockets are not supported in web browsers. ```typescript read(options: ReadOptions): Promise { console.log('TCP read attempted in web context:', options) return Promise.reject(new Error(this.ERROR_MESSAGE)) } ``` -------------------------------- ### Read Data From TCP Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Illustrates reading data from a TCP client. Allows specifying expected length, timeout, and desired encoding (UTF8, BASE64, HEX), with a fallback to BASE64 for un-decodable UTF8 data. ```swift // Example of reading data (actual implementation would involve call parameters) // let expectLen = 1024; // let timeout = 10; // let encoding = "utf8"; // or "base64", "hex" // let response = client.read(expectLen, timeout: timeout) ``` -------------------------------- ### Import Capacitor TCP Socket Plugin Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md Imports the necessary components from the plugin. The module is tree-shakeable, allowing you to import only what you need. ```typescript import { TcpSocket, DataEncoding } from 'capacitor-tcp-socket'; ``` ```typescript import { TcpSocket } from 'capacitor-tcp-socket'; // Plugin only ``` ```typescript import { DataEncoding } from 'capacitor-tcp-socket'; // Enum only ``` ```typescript import type { ConnectResult, ReadResult } from 'capacitor-tcp-socket'; // Types only ``` -------------------------------- ### Binary to Hex to Binary Conversion Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Illustrates converting binary data to a hexadecimal string representation and then decoding it back to binary. This is useful for representing binary data as text. ```typescript // Start with binary const binaryData = new Uint8Array([0x1B, 0x40, 0x20]); // Convert to hex const hex = Array.from(binaryData) .map(b => b.toString(16).padStart(2, '0')) .join(''); // "1b4020" // Send as hex await TcpSocket.send({ client: 0, data: hex, encoding: DataEncoding.HEX }); // Receive and decode const response = await TcpSocket.read({ client: 0, expectLen: 1024, encoding: DataEncoding.HEX }); const receivedBinary = new Uint8Array( response.result.split('').map((_, i) => { if (i % 2 === 0) { return parseInt(response.result.substr(i, 2), 16); } }).filter(Boolean) ); ``` -------------------------------- ### Read with Default Options Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Use default timeout and encoding when reading data. Requires client identifier and expected length. ```typescript const result = await TcpSocket.read({ client: 0, expectLen: 1024 // timeout defaults to 10 seconds // encoding defaults to UTF8 }); ``` -------------------------------- ### Implement Request-Response Pattern Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md Send a command to the server and wait for a response using TcpSocket.send and TcpSocket.read. Handles potential empty responses and specifies data encoding. ```typescript async function sendCommandAndWaitForResponse( client: number, command: string ): Promise { // Send command await TcpSocket.send({ client, data: command, encoding: DataEncoding.UTF8 }); // Wait for response const response = await TcpSocket.read({ client, expectLen: 2048, timeout: 10, encoding: DataEncoding.UTF8 }); if (response.result === '') { throw new Error('No response from server'); } return response.result; } ``` -------------------------------- ### Basic TCP Socket Operations in TypeScript Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/README.md Demonstrates connecting to a TCP server, sending data, reading responses, and disconnecting. Ensure the server IP and port are correct. The read operation includes parameters for expected data length and a timeout. ```typescript 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 }); 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); } }; ``` -------------------------------- ### Encoding Speed Comparison Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/data-encoding.md Illustrates the relative encoding speeds for UTF8, Hex, and Base64. UTF8 is the fastest due to direct byte mapping. ```plaintext UTF8: Fastest (direct byte mapping) Hex: Slow (string parsing) Base64: Medium (library decoding) ``` -------------------------------- ### iOS Client Management Implementation Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/README.md Illustrates how active socket connections are managed on iOS using an array of TCPClient objects. The client ID corresponds to the zero-based index. ```swift private var clients: [TCPClient] = [] ``` -------------------------------- ### Web Platform: TCP Not Supported, Use WebSocket Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/integration-guide.md The Web platform does not support TCP sockets directly. Always check the platform using Capacitor.getPlatform() before attempting to connect. Use WebSockets as an alternative for web clients. ```typescript // Web does not support TCP; always use platform check if (Capacitor.getPlatform() !== 'web') { await TcpSocket.connect({ ipAddress: '...' }); } else { // Use WebSocket instead const ws = new WebSocket('ws://...'); } ``` -------------------------------- ### Web Implementation Base Class Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md Defines the `TcpSocketWeb` class extending `WebPlugin`, serving as a stub for web browser environments where direct TCP connections are not supported. ```typescript export class TcpSocketWeb extends WebPlugin implements TcpSocketPlugin { private readonly ERROR_MESSAGE = 'TCP sockets are not supported in web browsers.'; // ... implementations } ``` -------------------------------- ### send() Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/tcp-socket.md Sends data to a connected TCP server with optional encoding. ```APIDOC ## send() ### Description Sends data to a connected TCP server with optional encoding. ### Method send ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **options** (SendOptions) - Required - Configuration object for sending data - **client** (number) - Required - Client identifier from a previous `connect()` call - **data** (string) - Required - Data string to send to the server - **encoding** (DataEncoding) - Optional - Encoding type for the data being sent (default: UTF8) ### Request Example ```typescript await TcpSocket.send({ client: clientId, data: 'Hello, TCP Server!', encoding: DataEncoding.UTF8 }); console.log('Data sent successfully'); ``` ### Advanced Request Example (Binary Data) ```typescript // Sending hex-encoded binary data const hexData = "48656C6C6F"; // "Hello" in hex await TcpSocket.send({ client: clientId, data: hexData, encoding: DataEncoding.HEX }); ``` ### Response #### Success Response (200) - None (void) ### Throws/Rejects - "Client not specified or invalid index" - "Client index out of range" - "No data provided" - "Unsupported encoding: {encoding}" - "Failed to decode data with encoding: {encoding}" - "Socket not connected" - "Send failed: {error message}" - On web: Always rejects with "TCP sockets are not supported in web browsers." ``` -------------------------------- ### Connect to Device on Local Network Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Connect to a TCP server using its IP address on the local network. The default port (9100) is used. ```typescript // Connect to device on local network await TcpSocket.connect({ ipAddress: '192.168.1.50' // Uses default port 9100 }); ``` -------------------------------- ### Read with Short Timeout Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/configuration.md Configure a short timeout for reading data from quick-response devices. Specify client, expected length, and timeout value. ```typescript const result = await TcpSocket.read({ client: 0, expectLen: 512, timeout: 2 }); ``` -------------------------------- ### Web Implementation: send() Method Stub Source: https://github.com/gee1k/capacitor-tcp-socket/blob/main/_autodocs/api-reference/plugin-implementations.md The `send` method in the web implementation logs the attempt and rejects the promise, indicating that TCP sockets are not supported in web browsers. ```typescript send(options: SendOptions): Promise { console.log('TCP send attempted in web context:', options) return Promise.reject(new Error(this.ERROR_MESSAGE)) } ```