Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

jamesthomp/react-native-tcp-socket

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Native TCP socket API for Android, iOS & macOS withSSL/TLS support. It allows you to create TCP client and server sockets, imitating Node'snet and Node'stls API functionalities (check the availableAPI for more information).

Table of Contents

Getting started

Install the library using either Yarn:

yarn add react-native-tcp-socket

or npm:

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

Overridingnet

Sincereact-native-tcp-socket offers the same API as Node's net, in case you want to import this module asnet or userequire('net') in your JavaScript, you must add the following lines to yourpackage.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'{importTcpSocketsfrom'react-native-tcp-socket';export=TcpSockets;}

If you want to avoid duplicatednet types, make sure not to use the defaultnode_modules/@types in yourtsconfig.json"typeRoots" property.

Check theexample app provided for a working example.

Overridingtls

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

  • TheServer class exported by default is non-TLS. In order to use the TLS server, you must use theTLSServer class. You may override the defaultServer class (tls.Server = tls.TLSServer). The same goes with thecreateServer() andconnect(). In order to use the TLS methods, you must use thecreateTLSServer() andconnectTLS() methods respectively. You may override the default methods (tls.createServer = tls.createTLSServer andtls.connect = tls.connectTLS).
  • Node'stls module requires the keys and certificates to be provided as a string. However, thereact-native-tcp-socket module requires them to be imported withrequire().

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'{importTcpSocketsfrom'react-native-tcp-socket';exportconstServer=TcpSockets.TLSServer;exportconstTLSSocket=TcpSockets.TLSSocket;exportconstconnect=TcpSockets.connectTLS;exportconstcreateServer=TcpSockets.createTLSServer;}

Check theexample app provided for a working example.

Using React Native >= 0.60

Linking the package manually is not required anymore withAutolinking.

  • iOS Platform:

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

  • Android Platform:

    Modify yourandroid/build.gradle configuration to matchminSdkVersion = 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 4096openssl req -new -key server-key.pem -out server-csr.pemopenssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pemopenssl pkcs12 -export -out server-keystore.p12 -inkey server-key.pem -in server-cert.pem

Note: Theserver-keystore.p12 must not have a password.

You will need ametro.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 amodule.exports object, create a key calledresolver with another object calledassetExts. The value ofassetExts 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), yourmetro.config.js should look like this:

const{getDefaultConfig}=require('metro-config');constdefaultConfig=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 clickLibrariesAdd Files to [your project's name]
  2. Go tonode_modulesreact-native-tcp-socket and addTcpSockets.xcodeproj
  3. In XCode, in the project navigator, select your project. AddlibTcpSockets.a to your project'sBuild PhasesLink Binary With Libraries
  4. Run your project (Cmd+R)<
Manually link the library on Android
  1. Open upandroid/app/src/main/java/[...]/MainApplication.java
  • Addimport com.asterinet.react.tcpsocket.TcpSocketPackage; to the imports at the top of the file
  • Addnew TcpSocketPackage() to the list returned by thegetPackages() method
  1. Append the following lines toandroid/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 inandroid/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 than0.60 you will need to upgrade before attempting to use the latest version.

react-native-tcp-socket versionRequired 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:

importTcpSocketfrom'react-native-tcp-socket';// const net = require('react-native-tcp-socket');// const tls = require('react-native-tcp-socket');

Client example

constoptions={port:port,host:'127.0.0.1',localAddress:'127.0.0.1',reuseAddress:true,// localPort: 20000,// interface: "wifi",};// Create socketconstclient=TcpSocket.createConnection(options,()=>{// Write on the socketclient.write('Hello server!');// Close socketclient.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

constserver=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

constoptions={port:port,host:'127.0.0.1',localAddress:'127.0.0.1',reuseAddress:true,// localPort: 20000,// interface: "wifi",ca:require('server-cert.pem'),};// Create socketconstclient=TcpSocket.connectTLS(options,()=>{// Write on the socketclient.write('Hello server!');// Close socketclient.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

constoptions={keystore:require('server-keystore.p12'),};constserver=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 toupdate your metro.config.js configuration.

API

net

Here are listed all methods implemented inreact-native-tcp-socket that imitate Node'snet API, their functionalities are equivalent to those provided by Node'snet (more info on#41). However, themethods whose interface differs from Node are marked in bold.

Socket

net.createConnection()

net.createConnection(options[, callback]) creates a TCP connection using the givenoptions. Theoptions parameter must be anobject with the following properties:

PropertyTypeiOS/macOSAndroidDescription
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 ishighly recommended to specify alocalAddress 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

Server.listen()

Server.listen(options[, callback]) creates a TCP server socket using the givenoptions. Theoptions parameter must be anobject with the following properties:

PropertyTypeiOS/macOSAndroidDescription
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 inreact-native-tcp-socket that imitate Node'stls API, their functionalities are equivalent to those provided by Node'stls. However, themethods whose interface differs from Node are marked in bold.

TLSSocket

tls.connectTLS()

tls.connectTLS(options[, callback]) creates a TLS socket connection using the givenoptions. Theoptions parameter must be anobject with the following properties:

PropertyTypeiOS/macOSAndroidDescription
ca<import>CA file (.pem format) to trust. Ifnull, it will use the device's default SSL trusted list. Useful for self-signed certificates.Check thedocumentation for generating such file.Default:null.
key<import>Private key file (.pem format).Check thedocumentation for generating such file.
cert<import>Public certificate file (.pem format).Check thedocumentation for generating such file.
androidKeyStore<string>Android KeyStore alias.
certAlias<string>Android KeyStore certificate alias.
keyAlias<string>Android KeyStore private key alias.
...<any>Any othersocket.connect() options not already listed.

TLSServer

Note: The TLS server is namedServer in Node's tls, but it is namedTLSServer inreact-native-tcp-socket in order to avoid confusion with theServer class.

tls.createTLSServer()

tls.createTLSServer([options][, secureConnectionListener]) creates a newtls.TLSServer. ThesecureConnectionListener, if provided, is automatically set as a listener for the'secureConnection' event. Theoptions parameter must be anobject with the following properties:

PropertyTypeiOS/macOSAndroidDescription
keystore<import>Required. Key store in PKCS#12 format with the server certificate and private key.Check thedocumentation for generating such file.

Maintainers

Acknowledgments

License

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

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java45.4%
  • JavaScript27.9%
  • Objective-C24.4%
  • Ruby2.3%

[8]ページ先頭

©2009-2025 Movatter.jp