Skip to content

Latest commit

 

History

History
53 lines (38 loc) · 2.63 KB

ws.md

File metadata and controls

53 lines (38 loc) · 2.63 KB

WebSocket

This library implements the WebSocket Web API and is meant to be a drop-in replacement for React Native's WebSocket implementation.

Under the hood, it uses:

During our benchmarking, we found that this WebSocket implementation is 2-3x faster than React Native's implementation under common scenarios and even up to 150x faster when streaming large binary data (such as images).

Usage

import { WebSocket, Blob } from 'react-native-fast-io';

// Create a new WebSocket instance
const ws = new WebSocket('wss://echo.websocket.org');

// Using event listeners (recommended)
ws.addEventListener('open', (event) => {
  console.log('Connected to server');
  ws.send('Hello Server!');
});

// Or using event handlers
ws.onopen = (event) => {
  console.log('Connected to server');
};

// Listen to messages
ws.addEventListener('message', (event) => {
  console.log('Received:', event.data);
});

// Send different types of data
ws.send('Plain text message');
ws.send(new Blob('string'));
ws.send(new Uint8Array([1, 2, 3, 4]));

// Close the connection when done
ws.close();

Note

When setting binaryType to 'blob', the library will dispatch MessageEvents with Blob objects. This is incompatible with React Native's Blob.

For more detailed information about the WebSocket API, check out the MDN WebSocket documentation.

Differences with React Native's WebSocket