react-native-real-time-nitro
npm install react-native-real-time-nitro
High-performance WebSocket client for React Native
A blazing-fast WebSocket library built with native C++ for maximum performance
---
๐ Native Performance | ๐ Secure by Default |
๐ฆ Binary Support | ๐๏ธ Auto Compression |
๐งต Thread-Safe | ๐ Cross-Platform |
---
This library requires react-native-nitro-modules as a peer dependency:
``bash`
npm install react-native-nitro-modules react-native-real-time-nitro
or
`bash`
yarn add react-native-nitro-modules react-native-real-time-nitro
๐ iOS ` | ๐ค Android No additional setup required โ |
---
`typescript
import { createWebSocket } from 'react-native-real-time-nitro'
const ws = createWebSocket()
// ๐ก Setup callbacks
ws.onOpen = () => console.log('โ
Connected')
ws.onMessage = (msg) => console.log('๐จ Received:', msg)
ws.onError = (error) => console.error('โ Error:', error)
ws.onClose = (code, reason) => console.log('๐ Closed:', code, reason)
// ๐ Connect
await ws.connect('wss://echo.websocket.org')
// ๐ค Send message
ws.send('Hello!')
// ๐ Close when done
ws.close(1000, 'Done')
`
---
#### createWebSocket(): WebSocket
Creates a new WebSocket instance.
`typescript
import { createWebSocket } from 'react-native-real-time-nitro'
const ws = createWebSocket()
`
---
๐ก connect(url: string, protocols?: string[]): Promise<void>
Connect to a WebSocket server.
Parameters:
- url - WebSocket URL (ws:// or wss://)protocols
- - Optional array of subprotocol names
Example:
`typescript`
await ws.connect('wss://example.com', ['chat', 'v1.protocol'])
๐ค send(message: string): void
Send a text message (only when connected).
Example:
`typescript`
ws.send('Hello server!')
> โ ๏ธ Note: Only call when ws.state === 1 (OPEN)
๐ฆ sendBinary(data: ArrayBuffer): void
Send binary data.
Example:
`typescript`
const buffer = new ArrayBuffer(4)
const view = new Uint8Array(buffer)
view[0] = 0x48 // 'H'
ws.sendBinary(buffer)
> โ ๏ธ Note: Only call when ws.state === 1 (OPEN)
๐ close(code?: number, reason?: string): void
Close the connection gracefully.
Parameters:
- code - Close code (default: 1000)reason
- - Close reason string
Example:
`typescript`
ws.close(1000, 'Normal closure')
๐ setPingInterval(intervalMs: number): void
Set keep-alive ping interval in milliseconds.
Example:
`typescript`
ws.setPingInterval(30000) // ping every 30 seconds
ws.setPingInterval(8000) // ping every 8 seconds
๐ setCAPath(path: string): void
Set custom CA certificate path for SSL/TLS verification.
Examples:
`typescript
// Use custom certificate
ws.setCAPath('/path/to/cert.pem')
// Disable verification (dev only)
ws.setCAPath('')
`
> ๐จ Warning: Empty path disables SSL verification. Use only in development!
---
| Property | Type | Description |
|----------|------|-------------|
| state | WebSocketState (readonly) | Current connection state |string
| url | (readonly) | Connected WebSocket URL |
#### Connection States
`typescript`
enum WebSocketState {
CONNECTING = 0, // ๐ Connection in progress
OPEN = 1, // โ
Connected and ready
CLOSING = 2, // โณ Closing in progress
CLOSED = 3 // ๐ Connection closed
}
Example:
`typescript`
if (ws.state === 1) {
ws.send('Message')
}
---
| Callback | Parameters | Description |
|----------|------------|-------------|
| onOpen | () => void | โ
Connection established |(message: string) => void
| onMessage | | ๐จ Text message received |(data: ArrayBuffer) => void
| onBinaryMessage | | ๐ฆ Binary data received |(error: string) => void
| onError | | โ Error occurred |(code: number, reason: string) => void
| onClose | | ๐ Connection closed |
Example:
`typescript`
ws.onOpen = () => console.log('โ
Connected!')
ws.onMessage = (msg) => console.log('๐จ', msg)
ws.onBinaryMessage = (data) => console.log('๐ฆ', new Uint8Array(data))
ws.onError = (error) => console.error('โ', error)
ws.onClose = (code, reason) => console.log('๐', code, reason)
---
`typescript
import { createWebSocket } from 'react-native-real-time-nitro'
import { useEffect } from 'react'
export default function Chat() {
useEffect(() => {
const ws = createWebSocket()
ws.onOpen = () => {
console.log('โ
Connected to chat')
ws.send('Hello everyone!')
}
ws.onMessage = (msg) => {
console.log('๐ฌ New message:', msg)
}
ws.connect('wss://chat-server.com')
return () => ws.close()
}, [])
return
}
`
`typescript
const ws = createWebSocket()
ws.onBinaryMessage = (data) => {
const view = new Uint8Array(data)
console.log('๐ฆ Received bytes:', view)
}
ws.onOpen = () => {
// Send binary data
const buffer = new ArrayBuffer(8)
const view = new Uint8Array(buffer)
view[0] = 0x48 // 'H'
view[1] = 0x65 // 'e'
view[2] = 0x6C // 'l'
view[3] = 0x6C // 'l'
view[4] = 0x6F // 'o'
ws.sendBinary(buffer)
}
await ws.connect('wss://binary-server.com')
`
`typescript
const ws = createWebSocket()
// โ
Use bundled CA certificates (recommended)
await ws.connect('wss://secure-server.com')
// ๐ง Or use custom certificate
ws.setCAPath('/path/to/custom-cert.pem')
await ws.connect('wss://secure-server.com')
// ๐จ Dev only: Disable verification
ws.setCAPath('')
await ws.connect('wss://dev-server.com')
`
`typescript
const ws = createWebSocket()
// Send ping every 30 seconds (30000 milliseconds)
ws.setPingInterval(30000)
await ws.connect('wss://server.com')
`
---
| Code | Name | Description |
|------|------|-------------|
| 1000 | ๐ข Normal Closure | Normal closure; connection completed |1001
| | ๐ช Going Away | Endpoint going away (e.g., server shutdown) |1002
| | โ Protocol Error | Protocol error detected |1003
| | ๐ซ Unsupported Data | Unsupported data type received |1006
| | โ ๏ธ Abnormal Closure | Abnormal closure (no close frame) |1008
| | ๐ Policy Violation | Message violates policy |1009
| | ๐ Message Too Big | Message too large to process |1011
| | ๐ฅ Internal Error | Internal server error |
---
> Problem: Cannot connect to WebSocket server
Solutions:
- โ
Verify URL starts with ws:// or wss://ws.setCAPath('')
- โ
Check server is running and accessible
- โ
For SSL issues, try (dev only)
- โ
Check network connectivity
> Problem: send() doesn't work
Solutions:
- โ
Ensure ws.state === 1 (OPEN state)onError
- โ
Check callback for error messagesonOpen
- โ
Verify server is accepting messages
- โ
Wait for callback before sending
> Problem: Certificate verification fails
Solutions:
- โ
Use setCAPath() with valid certificate bundlesetCAPath('')`
- โ
Ensure certificate includes intermediate certificates
- โ
For development, disable with
- โ
Check certificate expiration date
---
MIT ยฉ Hoang Tuan
---
---
Made with โค๏ธ by Hoang Tuan
Built with Nitro Modules โข libwebsockets โข mbedTLS