react native tcp socket

2025-12-07 0 674

reactnativetcpsocket

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support. It allows you to create TCP client and server sockets, imitating Node\’s net and Node\’s tls API functionalities (check the available API for more information).

Table of Contents

  • Getting started
    • Overriding net
    • Overriding tls
    • Using React Native >= 0.60
    • Self-Signed SSL (only available for React Native > 0.60)
    • Using React Native < 0.60
  • React Native Compatibility
  • Usage
    • Client example
    • Server example
    • TLS Client example
    • TLS Server example
  • API
    • net
      • Socket
      • Server
    • tls
      • TLSSocket
      • TLSServer
  • Maintainers
  • Acknowledgments
  • License

Getting started

Install the library using either Yarn:

yarn add react-native-tcp-socket

or npm:

npm install --save react-native-tcp-socket

Overriding net

Since react-native-tcp-socket offers the same API as Node\’s net, in case you want to import this module as net or use require(\'net\') in your JavaScript, you must add the following lines to your package.json file.

{
  \"react-native\": {
    \"net\": \"react-native-tcp-socket\"
  }
}

In addition, in order to obtain the TS types (or autocompletion) provided by this module, you must also add the following to your custom declarations file.

...
declare module \'net\' {
    import TcpSockets from \'react-native-tcp-socket\';
    export = TcpSockets;
}

If you want to avoid duplicated net types, make sure not to use the default node_modules/@types in your tsconfig.json \"typeRoots\" property.

Check the example app provided for a working example.

Overriding tls

The same applies to tls module. However, you should be aware of the following:

  • The Server class exported by default is non-TLS. In order to use the TLS server, you must use the TLSServer class. You may override the default Server class (tls.Server = tls.TLSServer). The same goes with the createServer() and connect(). In order to use the TLS methods, you must use the createTLSServer() and connectTLS() methods respectively. You may override the default methods (tls.createServer = tls.createTLSServer and tls.connect = tls.connectTLS).
  • Node\’s tls module requires the keys and certificates to be provided as a string. However, the react-native-tcp-socket module requires them to be imported with require().

In addition, in order to obtain the TS types (or autocompletion) provided by this module, you must also add the following to your custom declarations file.

...
declare module \'tls\' {
    import TcpSockets from \'react-native-tcp-socket\';
    export const Server = TcpSockets.TLSServer;
    export const TLSSocket = TcpSockets.TLSSocket;
    export const connect = TcpSockets.connectTLS;
    export const createServer = TcpSockets.createTLSServer;
}

Check the example app provided for a working example.

Using React Native >= 0.60

Linking the package manually is not required anymore with Autolinking.

  • iOS Platform:

    $ cd ios && pod install && cd .. # CocoaPods on iOS needs this extra step

  • Android Platform:

    Modify your android/build.gradle configuration to match minSdkVersion = 21:

    buildscript {
      ext {
        ...
        minSdkVersion = 21
        ...
      }
    

Self-Signed SSL (only available for React Native > 0.60)

In order to generate the required files (keys and certificates) for self-signed SSL, you can use the following command:

openssl genrsa -out server-key.pem 4096
openssl req -new -key server-key.pem -out server-csr.pem
openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem
openssl pkcs12 -export -out server-keystore.p12 -inkey server-key.pem -in server-cert.pem

Note: The server-keystore.p12 must not have a password.

You will need a metro.config.js file in order to use a self-signed SSL certificate. You should already have this file in your root project directory, but if you don\’t, create it.
Inside a module.exports object, create a key called resolver with another object called assetExts. The value of assetExts should be an array of the resource file extensions you want to support.

If you want to be able to use .pem and .p12 files (plus all the already supported files), your metro.config.js should look like this:

const {getDefaultConfig} = require(\'metro-config\');
const defaultConfig = getDefaultConfig.getDefaultValues(__dirname);

module.exports = {
  resolver: {
    assetExts: [...defaultConfig.resolver.assetExts, \'pem\', \'p12\'],
  },
  // ...
};

Using React Native < 0.60

You then need to link the native parts of the library for the platforms you are using. The easiest way to link the library is using the CLI tool by running this command from the root of your project:

$ react-native link react-native-tcp-socket

If you can\’t or don\’t want to use the CLI tool, you can also manually link the library using the instructions below (click on the arrow to show them):

Manually link the library on iOS
  1. In XCode, in the project navigator, right click LibrariesAdd Files to [your project\'s name]
  2. Go to node_modulesreact-native-tcp-socket and add TcpSockets.xcodeproj
  3. In XCode, in the project navigator, select your project. Add libTcpSockets.a to your project\’s Build PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)<
Manually link the library on Android
  1. Open up android/app/src/main/java/[...]/MainApplication.java
  • Add import com.asterinet.react.tcpsocket.TcpSocketPackage; to the imports at the top of the file
  • Add new TcpSocketPackage() to the list returned by the getPackages() method
  1. Append the following lines to android/settings.gradle:
    include \':react-native-tcp-socket\'
    project(\':react-native-tcp-socket\').projectDir = new File(rootProject.projectDir, 	\'../node_modules/react-native-tcp-socket/android\')
    
  2. Insert the following lines inside the dependencies block in android/app/build.gradle:
      implementation project(\':react-native-tcp-socket\')
    

React Native Compatibility

To use this library you need to ensure you are using the correct version of React Native. If you are using a version of React Native that is lower than 0.60 you will need to upgrade before attempting to use the latest version.

react-native-tcp-socket version Required React Native Version
6.X.X, 5.X.X, 4.X.X, 3.X.X >= 0.60.0
1.4.0 >= Unknown

Usage

Import the library:

import TcpSocket from \'react-native-tcp-socket\';
// const net = require(\'react-native-tcp-socket\');
// const tls = require(\'react-native-tcp-socket\');

Client example

const options = {
  port: port,
  host: \'127.0.0.1\',
  localAddress: \'127.0.0.1\',
  reuseAddress: true,
  // localPort: 20000,
  // interface: \"wifi\",
};

// Create socket
const client = TcpSocket.createConnection(options, () => {
  // Write on the socket
  client.write(\'Hello server!\');

  // Close socket
  client.destroy();
});

client.on(\'data\', function(data) {
  console.log(\'message was received\', data);
});

client.on(\'error\', function(error) {
  console.log(error);
});

client.on(\'close\', function(){
  console.log(\'Connection closed!\');
});

Server example

const server = TcpSocket.createServer(function(socket) {
  socket.on(\'data\', (data) => {
    socket.write(\'Echo server \' + data);
  });

  socket.on(\'error\', (error) => {
    console.log(\'An error ocurred with client socket \', error);
  });

  socket.on(\'close\', (error) => {
    console.log(\'Closed connection with \', socket.address());
  });
}).listen({ port: 12345, host: \'0.0.0.0\' });

server.on(\'error\', (error) => {
  console.log(\'An error ocurred with the server\', error);
});

server.on(\'close\', () => {
  console.log(\'Server closed connection\');
});

TLS Client example

const options = {
  port: port,
  host: \'127.0.0.1\',
  localAddress: \'127.0.0.1\',
  reuseAddress: true,
  // localPort: 20000,
  // interface: \"wifi\",
  ca: require(\'server-cert.pem\'),
};

// Create socket
const client = TcpSocket.connectTLS(options, () => {
  // Write on the socket
  client.write(\'Hello server!\');

  // Close socket
  client.destroy();
});

client.on(\'data\', function(data) {
  console.log(\'message was received\', data);
});

client.on(\'error\', function(error) {
  console.log(error);
});

client.on(\'close\', function(){
  console.log(\'Connection closed!\');
});

TLS Server example

const options = {
  keystore: require(\'server-keystore.p12\'),
};


const server = TcpSocket.createTLSServer(options, function(socket) {
  socket.on(\'data\', (data) => {
    socket.write(\'Echo server \' + data);
  });

  socket.on(\'error\', (error) => {
    console.log(\'An error ocurred with SSL client socket \', error);
  });

  socket.on(\'close\', (error) => {
    console.log(\'SSL closed connection with \', socket.address());
  });
}).listen({ port: 12345, host: \'0.0.0.0\' });

server.on(\'error\', (error) => {
  console.log(\'An error ocurred with the server\', error);
});

server.on(\'close\', () => {
  console.log(\'Server closed connection\');
});

Note: In order to use self-signed certificates make sure to update your metro.config.js configuration.

API

net

Here are listed all methods implemented in react-native-tcp-socket that imitate Node\’s net API, their functionalities are equivalent to those provided by Node\’s net (more info on #41). However, the methods whose interface differs from Node are marked in bold.

  • net.connect(options[, callback])
  • net.createConnection(options[, callback])
  • net.createServer([options][, connectionListener])
  • net.isIP(input)
  • net.isIPv4(input)
  • net.isIPv6(input)

Socket

  • Methods:
    • address()
    • destroy([error])
    • end([data][, encoding][, callback])
    • setEncoding([encoding])
    • setKeepAlive([enable][, initialDelay])initialDelay is ignored
    • setNoDelay([noDelay])
    • setTimeout(timeout[, callback])
    • write(data[, encoding][, callback])
    • pause()
    • ref()Will not have any effect
    • resume()
    • unref()Will not have any effect
  • Properties:
    • Inherited from Stream.Writable:
      • writableNeedDrain
    • bytesRead
    • bytesWritten
    • connecting
    • destroyed
    • localAddress
    • localPort
    • remoteAddress
    • remoteFamily
    • remotePort
    • pending
    • timeout
    • readyState
  • Events:
    • Inherited from Stream.Readable:
      • \'pause\'
      • \'resume\'
    • \'close\'
    • \'connect\'
    • \'data\'
    • \'drain\'
    • \'error\'
    • \'timeout\'
net.createConnection()

net.createConnection(options[, callback]) creates a TCP connection using the given options. The options parameter must be an object with the following properties:

Property Type iOS/macOS Android Description
port <number> Required. Port the socket should connect to.
host <string> Host the socket should connect to. IP address in IPv4 format or \'localhost\'. Default: \'localhost\'.
localAddress <string> Local address the socket should connect from. If not specified, the OS will decide. It is highly recommended to specify a localAddress to prevent overload errors and improve performance.
localPort <number> Local port the socket should connect from. If not specified, the OS will decide.
interface <string> Interface the socket should connect from. If not specified, it will use the current active connection. The options are: \'wifi\', \'ethernet\', \'cellular\'.
reuseAddress <boolean> Enable/disable the reuseAddress socket option. Default: true.

Note: The platforms marked as use the default value.

Server

  • Methods:
    • address()
    • listen(options[, callback])
    • close([callback])
    • getConnections(callback)
  • Properties:
    • listening
  • Events:
    • \'close\'
    • \'connection\'
    • \'error\'
    • \'listening\'
Server.listen()

Server.listen(options[, callback]) creates a TCP server socket using the given options. The options parameter must be an object with the following properties:

Property Type iOS/macOS Android Description
port <number> Required. Port the socket should listen to.
host <string> Host the socket should listen to. IP address in IPv4 format or \'localhost\'. Default: \'0.0.0.0\'.
reuseAddress <boolean> Enable/disable the reuseAddress socket option. Default: true.

Note: The platforms marked as use the default value.

tls

Here are listed all methods implemented in react-native-tcp-socket that imitate Node\’s tls API, their functionalities are equivalent to those provided by Node\’s tls. However, the methods whose interface differs from Node are marked in bold.

  • tls.connectTLS(options[, callback])
  • tls.createTLSServer([options][, secureConnectionListener])

TLSSocket

  • Methods:
    • All methods from Socket
    • getCertificate()
    • getPeerCertificate()
  • Properties:
    • All properties from Socket
  • Events:
    • All events from Socket
    • \'secureConnect\'
tls.connectTLS()

tls.connectTLS(options[, callback]) creates a TLS socket connection using the given options. The options parameter must be an object with the following properties:

Property Type iOS/macOS Android Description
ca <import> CA file (.pem format) to trust. If null, it will use the device\’s default SSL trusted list. Useful for self-signed certificates. Check the documentation for generating such file. Default: null.
key <import> | <string> Private key file (.pem format). Check the documentation for generating such file.
cert <import> | <string> Public certificate file (.pem format). Check the documentation for generating such file.
androidKeyStore <string> Android KeyStore alias.
certAlias <string> Android KeyStore certificate alias.
keyAlias <string> Android KeyStore private key alias.
... <any> Any other socket.connect() options not already listed.

TLSServer

Note: The TLS server is named Server in Node\’s tls, but it is named TLSServer in react-native-tcp-socket in order to avoid confusion with the Server class.

  • Methods:
    • All methods from Server
    • setSecureContext(options)
  • Properties:
    • All properties from Server
  • Events:
    • All events from Server
    • \'secureConnection\'
tls.createTLSServer()

tls.createTLSServer([options][, secureConnectionListener]) creates a new tls.TLSServer. The secureConnectionListener, if provided, is automatically set as a listener for the \'secureConnection\' event. The options parameter must be an object with the following properties:

Property Type iOS/macOS Android Description
keystore <import> Required. Key store in PKCS#12 format with the server certificate and private key. Check the documentation for generating such file.

Maintainers

  • Rapsssito

Acknowledgments

  • iOS part originally forked from @aprock react-native-tcp
  • react-native-udp

License

The library is released under the MIT license. For more information see LICENSE.

下载源码

通过命令行克隆项目:

git clone https://github.com/Rapsssito/react-native-tcp-socket.git

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 开发教程 react native tcp socket https://www.zuozi.net/31465.html

hfuu_shop
上一篇: hfuu_shop
SPA asp.net api vuejs
下一篇: SPA asp.net api vuejs
常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务