Bereaksi API Socket TCP asli untuk Android, iOS & MacOS dengan dukungan SSL/TLS . Ini memungkinkan Anda untuk membuat soket klien dan server TCP, meniru jaring Node dan fungsi API TLS Node (periksa API yang tersedia untuk informasi lebih lanjut).
nettls utamaInstal perpustakaan menggunakan kedua benang:
yarn add react-native-tcp-socket
atau NPM:
npm install --save react-native-tcp-socket
net Karena react-native-tcp-socket menawarkan API yang sama dengan jaring Node, jika Anda ingin mengimpor modul ini sebagai net atau penggunaan require('net') di javascript Anda, Anda harus menambahkan baris berikut ke file package.json Anda.
{
"react-native" : {
"net" : " react-native-tcp-socket "
}
}Selain itu, untuk mendapatkan jenis TS (atau pelengkapan otomatis) yang disediakan oleh modul ini, Anda juga harus menambahkan yang berikut ke file deklarasi khusus Anda.
...
declare module 'net' {
import TcpSockets from 'react-native-tcp-socket' ;
export = TcpSockets ;
} Jika Anda ingin menghindari tipe net yang duplikat, pastikan untuk tidak menggunakan node_modules/@types default di properti tsconfig.json Anda "typeRoots" .
Periksa contoh aplikasi yang disediakan untuk contoh yang berfungsi.
tls utama Hal yang sama berlaku untuk modul tls . Namun, Anda harus mengetahui hal -hal berikut:
Server yang diekspor secara default adalah non-TLS. Untuk menggunakan server TLS, Anda harus menggunakan kelas TLSServer . Anda dapat mengganti kelas Server default ( tls.Server = tls.TLSServer ). Hal yang sama berlaku dengan createServer() dan connect() . Untuk menggunakan metode TLS, Anda harus menggunakan metode createTLSServer() dan connectTLS() masing -masing. Anda dapat mengganti metode default ( tls.createServer = tls.createTLSServer dan tls.connect = tls.connectTLS ).tls Node membutuhkan kunci dan sertifikat untuk disediakan sebagai string. Namun, modul react-native-tcp-socket mengharuskan mereka untuk diimpor dengan require() .Selain itu, untuk mendapatkan jenis TS (atau pelengkapan otomatis) yang disediakan oleh modul ini, Anda juga harus menambahkan yang berikut ke file deklarasi khusus Anda.
...
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 ;
}Periksa contoh aplikasi yang disediakan untuk contoh yang berfungsi.
Menghubungkan paket secara manual tidak diperlukan lagi dengan autolinking.
Platform iOS:
$ cd ios && pod install && cd .. # cocoapods di iOS membutuhkan langkah tambahan ini
Platform Android:
Ubah konfigurasi android/build.gradle Anda agar sesuai dengan minSdkVersion = 21 :
buildscript {
ext {
...
minSdkVersion = 21
...
}
Untuk menghasilkan file yang diperlukan (kunci dan sertifikat) untuk SSL yang ditandatangani sendiri, Anda dapat menggunakan perintah berikut:
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
Catatan: server-keystore.p12 tidak boleh memiliki kata sandi.
Anda akan memerlukan file metro.config.js untuk menggunakan sertifikat SSL yang ditandatangani sendiri. Anda seharusnya sudah memiliki file ini di direktori proyek root Anda, tetapi jika tidak, buatlah. Di dalam objek module.exports , buat kunci yang disebut resolver dengan objek lain yang disebut assetExts . Nilai assetExts harus berupa array ekstensi file sumber daya yang ingin Anda dukung.
Jika Anda ingin dapat menggunakan file .pem dan .p12 (ditambah semua file yang sudah didukung), metro.config.js Anda akan terlihat seperti ini:
const { getDefaultConfig } = require ( 'metro-config' ) ;
const defaultConfig = getDefaultConfig . getDefaultValues ( __dirname ) ;
module . exports = {
resolver : {
assetExts : [ ... defaultConfig . resolver . assetExts , 'pem' , 'p12' ] ,
} ,
// ...
} ; Anda kemudian perlu menautkan bagian asli perpustakaan untuk platform yang Anda gunakan. Cara termudah untuk menautkan perpustakaan adalah menggunakan alat CLI dengan menjalankan perintah ini dari akar proyek Anda:
$ react-native link react-native-tcp-socket
Jika Anda tidak dapat atau tidak ingin menggunakan alat CLI, Anda juga dapat menautkan secara manual perpustakaan menggunakan instruksi di bawah ini (klik panah untuk menunjukkannya):
Libraries klik kanan Add Files to [your project's name]node_modules react-native-tcp-socket dan tambahkan TcpSockets.xcodeprojlibTcpSockets.a ke Link Binary With Libraries Build Phases proyek Anda dengan perpustakaanCmd+R ) <android/app/src/main/java/[...]/MainApplication.javaimport com.asterinet.react.tcpsocket.TcpSocketPackage; ke impor di bagian atas filenew TcpSocketPackage() ke daftar yang dikembalikan dengan metode getPackages()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')
android/app/build.gradle : implementation project(':react-native-tcp-socket')
Untuk menggunakan perpustakaan ini, Anda perlu memastikan Anda menggunakan versi React Native yang benar. Jika Anda menggunakan versi Native React yang lebih rendah dari 0.60 Anda perlu meningkatkan sebelum mencoba menggunakan versi terbaru.
Versi react-native-tcp-socket | Diperlukan Versi Native React |
|---|---|
6.XX , 5.XX , 4.XX , 3.XX | >= 0.60.0 |
1.4.0 | >= Unknown |
Impor Perpustakaan:
import TcpSocket from 'react-native-tcp-socket' ;
// const net = require('react-native-tcp-socket');
// const tls = require('react-native-tcp-socket'); 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!' ) ;
} ) ; 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' ) ;
} ) ; 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!' ) ;
} ) ; 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' ) ;
} ) ;Catatan: Untuk menggunakan sertifikat yang ditandatangani sendiri, pastikan untuk memperbarui konfigurasi metro.config.js Anda.
Berikut ini terdaftar semua metode yang diimplementasikan dalam react-native-tcp-socket yang meniru API bersih Node, fungsinya setara dengan yang disediakan oleh Node's Net (info lebih lanjut tentang #41). Namun, metode yang antarmasinya berbeda dari simpul ditandai dengan huruf tebal .
net.connect(options[, callback])net.createConnection(options[, callback])net.createServer(connectionListener)net.isIP(input)net.isIPv4(input)net.isIPv6(input)address()destroy([error])end([data][, encoding][, callback])setEncoding([encoding])setKeepAlive([enable][, initialDelay]) - initialDelay diabaikansetNoDelay([noDelay])setTimeout(timeout[, callback])write(data[, encoding][, callback])pause()ref() - tidak akan memiliki efek apapunresume()unref() - tidak akan memiliki efek apapunStream.Writable .writableNeedDrainbytesReadbytesWrittenconnectingdestroyedlocalAddresslocalPortremoteAddressremoteFamilyremotePortpendingtimeoutreadyStateStream.Readable . Dapat dibaca:'pause''resume''close''connect''data''drain''error''timeout'net.createConnection() net.createConnection(options[, callback]) membuat koneksi TCP menggunakan options yang diberikan. Parameter options harus menjadi object dengan properti berikut:
| Milik | Jenis | iOS/macOS | Android | Keterangan |
|---|---|---|---|---|
port | <number> | Diperlukan . Port soket harus terhubung ke. | ||
host | <string> | Host soket harus terhubung ke. Alamat IP dalam format IPv4 atau 'localhost' . Default : 'localhost' . | ||
localAddress | <string> | Alamat lokal soket harus terhubung dari. Jika tidak ditentukan, OS akan memutuskan. Sangat disarankan untuk menentukan localAddress untuk mencegah kesalahan berlebih dan meningkatkan kinerja. | ||
localPort | <number> | Port lokal soket harus terhubung dari. Jika tidak ditentukan, OS akan memutuskan. | ||
interface | <string> | Antarmuka soket harus terhubung dari. Jika tidak ditentukan, itu akan menggunakan koneksi aktif saat ini. Pilihannya adalah: 'wifi', 'ethernet', 'cellular' . | ||
reuseAddress | <boolean> | Aktifkan/Nonaktifkan Opsi Soket ReuseAddress. Default : true . |
Catatan : Platform yang ditandai sebagai Gunakan nilai default.
address()listen(options[, callback])close([callback])getConnections(callback)listening'close''connection''error''listening'Server.listen() Server.listen(options[, callback]) membuat soket server TCP menggunakan options yang diberikan. Parameter options harus menjadi object dengan properti berikut:
| Milik | Jenis | iOS/macOS | Android | Keterangan |
|---|---|---|---|---|
port | <number> | Diperlukan . Port soket yang harus didengarkan. | ||
host | <string> | Host soket yang harus didengarkan. Alamat IP dalam format IPv4 atau 'localhost' . Default : '0.0.0.0' . | ||
reuseAddress | <boolean> | Aktifkan/Nonaktifkan Opsi Soket ReuseAddress. Default : true . |
Catatan : Platform yang ditandai sebagai Gunakan nilai default.
Berikut ini terdaftar semua metode yang diterapkan dalam react-native-tcp-socket yang meniru API TLS Node, fungsinya setara dengan yang disediakan oleh TLS Node. Namun, metode yang antarmasinya berbeda dari simpul ditandai dengan huruf tebal .
tls.connectTLS(options[, callback])tls.createTLSServer([options][, secureConnectionListener])SocketgetCertificate() Android sajagetPeerCertificate() Android sajaSocketSocket'secureConnect'tls.connectTLS() tls.connectTLS(options[, callback]) membuat koneksi soket TLS menggunakan options yang diberikan. Parameter options harus menjadi object dengan properti berikut:
| Milik | Jenis | iOS/macOS | Android | Keterangan |
|---|---|---|---|---|
ca | <import> | File ca (format .pem) untuk dipercaya. Jika null , itu akan menggunakan daftar tepercaya SSL default perangkat. Berguna untuk sertifikat yang ditandatangani sendiri. Periksa dokumentasi untuk menghasilkan file tersebut . Default : null . | ||
key | <import> | File kunci pribadi (format .pem). Periksa dokumentasi untuk menghasilkan file tersebut . | ||
cert | <import> | File Sertifikat Publik (format .pem). Periksa dokumentasi untuk menghasilkan file tersebut . | ||
androidKeyStore | <string> | Alias Keystore Android. | ||
certAlias | <string> | Alias Sertifikat Keystore Android. | ||
keyAlias | <string> | Android Keystore Private Key Alias. | ||
... | <any> | Opsi socket.connect() lainnya yang belum terdaftar. |
Catatan : Server TLS dinamai Server di Node TLS, tetapi dinamai TLSServer dalam react-native-tcp-socket untuk menghindari kebingungan dengan kelas Server .
ServersetSecureContext(options)ServerServer'secureConnection'tls.createTLSServer() tls.createTLSServer([options][, secureConnectionListener]) membuat tls.TLSServer baru. secureConnectionListener , jika disediakan, secara otomatis ditetapkan sebagai pendengar untuk acara 'secureConnection' . Parameter options harus menjadi object dengan properti berikut:
| Milik | Jenis | iOS/macOS | Android | Keterangan |
|---|---|---|---|---|
keystore | <import> | Diperlukan . Toko kunci dalam format PKCS#12 dengan sertifikat server dan kunci pribadi. Periksa dokumentasi untuk menghasilkan file tersebut . |
Perpustakaan dirilis di bawah lisensi MIT. Untuk informasi lebih lanjut, lihat LICENSE .