11# capacitor-tcp-socket
22
3- A TCP Socket Plugin for capacitor
3+ A TCP Socket Plugin for Capacitor, providing TCP communication capabilities in mobile applications.
44
5- Thanks [ @ottimis ] ( https://www.npmjs.com/package/@ottimis/tcp-socket )
5+ Thanks to [ @ottimis ] ( https://www.npmjs.com/package/@ottimis/tcp-socket )
66
7- ## Install
7+ ## Installation
88
99``` bash
1010npm install capacitor-tcp-socket
1111npx cap sync
1212```
1313
14+ ## Basic Usage
15+
16+ ``` typescript
17+ import { TcpSocket } from ' capacitor-tcp-socket' ;
18+
19+ // Connect to TCP server
20+ const connect = async () => {
21+ try {
22+ const result = await TcpSocket .connect ({
23+ ipAddress: ' 192.168.1.100' ,
24+ port: 9100
25+ });
26+ console .log (` Connected with client ID: ${result .client } ` );
27+ return result .client ;
28+ } catch (error ) {
29+ console .error (' Connection failed:' , error );
30+ }
31+ };
32+
33+ // Send data
34+ const sendData = async (clientId : number ) => {
35+ try {
36+ await TcpSocket .send ({
37+ client: clientId ,
38+ data: ' Hello, TCP Server!'
39+ });
40+ console .log (' Data sent successfully' );
41+ } catch (error ) {
42+ console .error (' Send failed:' , error );
43+ }
44+ };
45+
46+ // Read data
47+ const readData = async (clientId : number ) => {
48+ try {
49+ const result = await TcpSocket .read ({
50+ client: clientId ,
51+ expectLen: 1024 , // Expected maximum bytes to read
52+ timeout: 10 // Timeout in seconds, iOS only
53+ });
54+ console .log (' Received data:' , result .result );
55+ return result .result ;
56+ } catch (error ) {
57+ console .error (' Read failed:' , error );
58+ }
59+ };
60+
61+ // Disconnect
62+ const disconnect = async (clientId : number ) => {
63+ try {
64+ const result = await TcpSocket .disconnect ({
65+ client: clientId
66+ });
67+ console .log (` Disconnected client: ${result .client } ` );
68+ } catch (error ) {
69+ console .error (' Disconnect failed:' , error );
70+ }
71+ };
72+
73+ // Usage example
74+ const main = async () => {
75+ const clientId = await connect ();
76+ if (clientId !== undefined ) {
77+ await sendData (clientId );
78+ const data = await readData (clientId );
79+ await disconnect (clientId );
80+ }
81+ };
82+ ```
83+
84+ ## Working with Different Encodings
85+
86+ This plugin supports multiple data encodings for handling various types of data:
87+
88+ ### Using UTF-8 Encoding (Default)
89+
90+ ``` typescript
91+ import { TcpSocket , DataEncoding } from ' capacitor-tcp-socket' ;
92+
93+ // Send text data using UTF-8 encoding
94+ await TcpSocket .send ({
95+ client: clientId ,
96+ data: ' Hello, World!' ,
97+ encoding: DataEncoding .UTF8 // Optional, UTF8 is the default
98+ });
99+
100+ // Read data as UTF-8 text
101+ const result = await TcpSocket .read ({
102+ client: clientId ,
103+ expectLen: 1024 ,
104+ encoding: DataEncoding .UTF8 // Optional, UTF8 is the default
105+ });
106+
107+ console .log (' Received text:' , result .result );
108+ console .log (' Received encoding:' , result .encoding );
109+ ```
110+
111+ ### Using Base64 Encoding for Binary Data
112+
113+ ``` typescript
114+ import { TcpSocket , DataEncoding } from ' capacitor-tcp-socket' ;
115+
116+ // Send binary data using Base64 encoding
117+ const binaryData = new Uint8Array ([0x48 , 0x65 , 0x6C , 0x6C , 0x6F ]); // "Hello" in ASCII
118+ const base64Data = btoa (String .fromCharCode .apply (null , binaryData ));
119+
120+ await TcpSocket .send ({
121+ client: clientId ,
122+ data: base64Data ,
123+ encoding: DataEncoding .BASE64
124+ });
125+
126+ // Read binary data as Base64
127+ const result = await TcpSocket .read ({
128+ client: clientId ,
129+ expectLen: 1024 ,
130+ encoding: DataEncoding .BASE64
131+ });
132+
133+ // Convert Base64 back to binary if needed
134+ const binaryResult = new Uint8Array (
135+ atob (result .result )
136+ .split (' ' )
137+ .map (c => c .charCodeAt (0 ))
138+ );
139+ ```
140+
141+ ### Using Hexadecimal Encoding
142+
143+ ``` typescript
144+ import { TcpSocket , DataEncoding } from ' capacitor-tcp-socket' ;
145+
146+ // Send data using hex encoding
147+ const hexData = " 48656C6C6F" ; // "Hello" in hex
148+
149+ await TcpSocket .send ({
150+ client: clientId ,
151+ data: hexData ,
152+ encoding: DataEncoding .HEX
153+ });
154+
155+ // Read data as hex string
156+ const result = await TcpSocket .read ({
157+ client: clientId ,
158+ expectLen: 1024 ,
159+ encoding: DataEncoding .HEX
160+ });
161+
162+ console .log (' Received hex data:' , result .result );
163+ // Example output: "48656C6C6F"
164+
165+ // Convert hex to binary if needed
166+ function hexToBytes(hex ) {
167+ const bytes = [];
168+ for (let c = 0 ; c < hex .length ; c += 2 ) {
169+ bytes .push (parseInt (hex .substr (c , 2 ), 16 ));
170+ }
171+ return new Uint8Array (bytes );
172+ }
173+
174+ const binaryFromHex = hexToBytes (result .result );
175+ ```
176+
177+ ## Platform-Specific Considerations
178+
179+ ### Web
180+ - Not supported on the web platform.
181+
182+ ### iOS
183+ - iOS implementation uses the SwiftSocket library for TCP functionality.
184+ - Supports setting a timeout for read operations (via the ` timeout ` parameter).
185+
186+ ### Android
187+ - Android implementation uses the standard Java Socket API.
188+ - Currently, the read timeout parameter is not supported on Android.
189+
190+ ## Example Project
191+
192+ Check out the [ example] ( https://github.com/gee1k/capacitor-tcp-socket/tree/master/example ) directory to see a complete sample application.
193+
194+ Running the example app:
195+
196+ ``` bash
197+ cd example
198+ npm install
199+ npm start
200+ ```
201+
14202## API
15203
16204<docgen-index >
@@ -20,21 +208,27 @@ npx cap sync
20208* [ ` read(...) ` ] ( #read )
21209* [ ` disconnect(...) ` ] ( #disconnect )
22210* [ Interfaces] ( #interfaces )
211+ * [ Enums] ( #enums )
23212
24213</docgen-index >
25214
26215<docgen-api >
27216<!-- Update the source file JSDoc comments and rerun docgen to update the docs below-->
28217
218+ TCP Socket Plugin interface for Capacitor
219+ Provides methods for TCP socket communication
220+
29221### connect(...)
30222
31223``` typescript
32224connect (options : ConnectOptions ) => Promise < ConnectResult >
33225```
34226
35- | Param | Type |
36- | ------------- | --------------------------------------------------------- |
37- | ** ` options ` ** | <code ><a href =" #connectoptions " >ConnectOptions</a ></code > |
227+ Connects to a TCP server
228+
229+ | Param | Type | Description |
230+ | ------------- | --------------------------------------------------------- | ------------------------------------------------ |
231+ | ** ` options ` ** | <code ><a href =" #connectoptions " >ConnectOptions</a ></code > | Connection options including IP address and port |
38232
39233** Returns:** <code >Promise< ; <a href =" #connectresult " >ConnectResult</a >> ; </code >
40234
@@ -47,9 +241,11 @@ connect(options: ConnectOptions) => Promise<ConnectResult>
47241send (options : SendOptions ) => Promise < void >
48242```
49243
50- | Param | Type |
51- | ------------- | --------------------------------------------------- |
52- | ** ` options ` ** | <code ><a href =" #sendoptions " >SendOptions</a ></code > |
244+ Sends data to a connected TCP server
245+
246+ | Param | Type | Description |
247+ | ------------- | --------------------------------------------------- | --------------------------------------------------- |
248+ | ** ` options ` ** | <code ><a href =" #sendoptions " >SendOptions</a ></code > | Send options including client ID, data and encoding |
53249
54250--------------------
55251
@@ -60,9 +256,11 @@ send(options: SendOptions) => Promise<void>
60256read (options : ReadOptions ) => Promise < ReadResult >
61257```
62258
63- | Param | Type |
64- | ------------- | --------------------------------------------------- |
65- | ** ` options ` ** | <code ><a href =" #readoptions " >ReadOptions</a ></code > |
259+ Reads data from a connected TCP server
260+
261+ | Param | Type | Description |
262+ | ------------- | --------------------------------------------------- | ------------------------------------------------------------- |
263+ | ** ` options ` ** | <code ><a href =" #readoptions " >ReadOptions</a ></code > | Read options including client ID, expected length and timeout |
66264
67265** Returns:** <code >Promise< ; <a href =" #readresult " >ReadResult</a >> ; </code >
68266
@@ -75,9 +273,11 @@ read(options: ReadOptions) => Promise<ReadResult>
75273disconnect (options : DisconnectOptions ) => Promise < DisconnectResult >
76274```
77275
78- | Param | Type |
79- | ------------- | --------------------------------------------------------------- |
80- | ** ` options ` ** | <code ><a href =" #disconnectoptions " >DisconnectOptions</a ></code > |
276+ Disconnects from a TCP server
277+
278+ | Param | Type | Description |
279+ | ------------- | --------------------------------------------------------------- | --------------------------------- |
280+ | ** ` options ` ** | <code ><a href =" #disconnectoptions " >DisconnectOptions</a ></code > | Disconnect options with client ID |
81281
82282** Returns:** <code >Promise< ; <a href =" #disconnectresult " >DisconnectResult</a >> ; </code >
83283
@@ -89,54 +289,83 @@ disconnect(options: DisconnectOptions) => Promise<DisconnectResult>
89289
90290#### ConnectResult
91291
92- | Prop | Type |
93- | ------------ | ------------------- |
94- | ** ` client ` ** | <code >number</code > |
292+ Result of a successful connection
293+
294+ | Prop | Type | Description |
295+ | ------------ | ------------------- | ---------------------------------------------------- |
296+ | ** ` client ` ** | <code >number</code > | Client ID that can be used for subsequent operations |
95297
96298
97299#### ConnectOptions
98300
99- | Prop | Type |
100- | --------------- | ------------------- |
101- | ** ` ipAddress ` ** | <code >string</code > |
102- | ** ` port ` ** | <code >number</code > |
301+ Options for connecting to a TCP server
302+
303+ | Prop | Type | Description | Default |
304+ | --------------- | ------------------- | -------------------------------------- | ----------------- |
305+ | ** ` ipAddress ` ** | <code >string</code > | IP address of the server to connect to | |
306+ | ** ` port ` ** | <code >number</code > | Port number of the TCP server | <code >9100</code > |
103307
104308
105309#### SendOptions
106310
107- | Prop | Type |
108- | ------------ | ------------------- |
109- | ** ` client ` ** | <code >number</code > |
110- | ** ` data ` ** | <code >string</code > |
311+ Options for sending data to a TCP server
312+
313+ | Prop | Type | Description | Default |
314+ | -------------- | ----------------------------------------------------- | -------------------------------------- | ------------------------------ |
315+ | ** ` client ` ** | <code >number</code > | Client ID from a previous connect call | |
316+ | ** ` data ` ** | <code >string</code > | Data string to send to the server | |
317+ | ** ` encoding ` ** | <code ><a href =" #dataencoding " >DataEncoding</a ></code > | Encoding type for the data | <code >DataEncoding.UTF8</code > |
111318
112319
113320#### ReadResult
114321
115- | Prop | Type |
116- | ------------ | ------------------- |
117- | ** ` result ` ** | <code >string</code > |
322+ Result of a read operation
323+
324+ | Prop | Type | Description |
325+ | -------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
326+ | ** ` result ` ** | <code >string</code > | Data read from the server Can be UTF-8 string, Base64 encoded string, or Hex string depending on the encoding option |
327+ | ** ` encoding ` ** | <code ><a href =" #dataencoding " >DataEncoding</a ></code > | The encoding of the returned result |
118328
119329
120330#### ReadOptions
121331
122- | Prop | Type | Description |
123- | --------------- | ------------------- | ---------------------------------------------------------- |
124- | ** ` client ` ** | <code >number</code > | |
125- | ** ` expectLen ` ** | <code >number</code > | |
126- | ** ` timeout ` ** | <code >number</code > | timeout in seconds. default: 10 only ios supports timeout. |
332+ Options for reading data from a TCP server
333+
334+ | Prop | Type | Description | Default |
335+ | --------------- | ----------------------------------------------------- | -------------------------------------- | ------------------------------ |
336+ | ** ` client ` ** | <code >number</code > | Client ID from a previous connect call | |
337+ | ** ` expectLen ` ** | <code >number</code > | Expected number of bytes to read | |
338+ | ** ` timeout ` ** | <code >number</code > | Read timeout in seconds | <code >10</code > |
339+ | ** ` encoding ` ** | <code ><a href =" #dataencoding " >DataEncoding</a ></code > | Preferred encoding for returned data | <code >DataEncoding.UTF8</code > |
127340
128341
129342#### DisconnectResult
130343
131- | Prop | Type |
132- | ------------ | ------------------- |
133- | ** ` client ` ** | <code >number</code > |
344+ Result of a disconnect operation
345+
346+ | Prop | Type | Description |
347+ | ------------ | ------------------- | ------------------------------- |
348+ | ** ` client ` ** | <code >number</code > | Client ID that was disconnected |
134349
135350
136351#### DisconnectOptions
137352
138- | Prop | Type |
139- | ------------ | ------------------- |
140- | ** ` client ` ** | <code >number</code > |
353+ Options for disconnecting from a TCP server
354+
355+ | Prop | Type | Description |
356+ | ------------ | ------------------- | -------------------------------------- |
357+ | ** ` client ` ** | <code >number</code > | Client ID from a previous connect call |
358+
359+
360+ ### Enums
361+
362+
363+ #### DataEncoding
364+
365+ | Members | Value | Description |
366+ | ------------ | --------------------- | ------------------- |
367+ | ** ` UTF8 ` ** | <code >'utf8'</code > | UTF-8 text encoding |
368+ | ** ` BASE64 ` ** | <code >'base64'</code > | Base64 encoded data |
369+ | ** ` HEX ` ** | <code >'hex'</code > | Hexadecimal string |
141370
142371</docgen-api >
0 commit comments