Constructor
string
required
The URL to connect to. Must use
ws:// or wss:// protocol.string | string[]
Optional subprotocol(s) to use. Can be a single string or array of strings.
object
Properties
State Constants
number
default:"0"
Connection is being established
number
default:"1"
Connection is open and ready to communicate
number
default:"2"
Connection is in the process of closing
number
default:"3"
Connection is closed
Instance Properties
number
Current connection state. One of the state constants above.
string
The URL of the WebSocket connection
string
The subprotocol selected by the server
number
Number of bytes queued to be sent
'blob' | 'arraybuffer'
Type of binary data received. Can be set to
'blob' or 'arraybuffer'.Methods
send()
string | ArrayBuffer | ArrayBufferView | Blob
required
Data to send:
- string: Text message
- ArrayBuffer: Binary data
- ArrayBufferView: Typed array (Uint8Array, etc.)
- Blob: Binary large object
INVALID_STATE_ERR if called before connection is open.
close()
number
default:"1000"
Close status code. Default is 1000 (normal closure).Common codes:
1000- Normal closure1001- Going away1002- Protocol error1003- Unsupported data1006- Abnormal closure (no close frame received)
string
Human-readable reason for closing
ping()
INVALID_STATE_ERR if called before connection is open.
Event Handlers
onopen
onmessage
event.data can be:
stringfor text messagesArrayBufferifbinaryTypeis set to'arraybuffer'BlobifbinaryTypeis set to'blob'
onerror
onclose
code- Close status codereason- Close reason string
Examples
Basic Connection
React Component
With Custom Headers
Binary Data with ArrayBuffer
Binary Data with Blob
Automatic Reconnection
Ping/Keep-Alive
JSON Messages
Notes
- WebSocket follows the browser WebSocket API specification
- Secure connections (
wss://) are recommended for production - On iOS, configure App Transport Security to allow non-HTTPS connections if needed
- Binary data requires setting
binaryTypeproperty - Use
ping()for keep-alive on long-lived connections - Always clean up WebSocket connections in component unmount
- Consider using libraries like
socket.io-clientfor advanced features (rooms, automatic reconnection, etc.) - Handle reconnection logic for production applications
- Be mindful of battery usage with persistent connections