Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

react-native-tcp-socket

> 前端框架
Open source

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support.

391 stars0 likes3 views
WebsiteGitHub

About

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support.

react-native-tcp-socket

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 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:

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

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

Using React Native

Manually link the library on iOS

  1. In XCode, in the project navigator, right click Libraries ➜ Add Files to [your project's name]
  2. Go to node_modules ➜ react-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 Phases ➜ Link 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:

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

Client example

javascript
const options = {
  port: port,
  host: '127.0.0.1',
  localAddress: '127.0.0.1',
  reuseAddress: true,
  // connectTimeout: 5000,
  // 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

javascript
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

…

TLS Server example

…

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 `` ✅ ✅ Required. Port the socket should connect to.
host `` ✅ ✅ Host the socket should connect to. IP address in IPv4 format or 'localhost'. Default: 'localhost'.
localAddress `` ✅ ✅ 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 `` ✅ ✅ Local port the socket should connect from. If not specified, the OS will decide.
connectTimeout `` ✅ ✅ Connects the socket to a server with a configurable connection timeout (in milliseconds). If the timeout expires before the connection is established, the operation fails. When no timeout is specified, the connection will block indefinitely until it either succeeds or an error occurs.
interface `` ❌ ✅ Interface the socket should connect from. If not specified, it will use the current active connection. The options are: 'wifi', 'ethernet', 'cellular'.
reuseAddress `` ❌ ✅ Enable/disable the reuseAddress socket option. Default: true.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javaandroidiosnetnetwork

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架