capacitor-websocket-server
v0.0.1
Published
Capacitor WebSocket Server Plugin
Maintainers
Readme
capacitor-websocket-server
A Capacitor plugin that allows you to run a WebSocket server on iOS and Android devices.
Features
- Start/stop a WebSocket server on any port
- Accept multiple client connections
- Send text and binary messages
- Origin validation for security
- WebSocket sub-protocol negotiation
- TCP_NODELAY option for low-latency messaging
- Get network interface addresses
Install
npm install capacitor-websocket-server
npx cap syncUsage
import { WebsocketServer } from 'capacitor-websocket-server';
// Set up event listeners
WebsocketServer.addListener('onOpen', (event) => {
console.log('Client connected:', event.connection.uuid);
console.log('Remote address:', event.connection.remoteAddr);
});
WebsocketServer.addListener('onMessage', (event) => {
console.log('Message from', event.uuid);
if (event.isBinary) {
// Binary message - decode from base64
const binaryData = atob(event.message);
console.log('Binary message received');
} else {
// Text message
console.log('Text message:', event.message);
// Echo the message back
WebsocketServer.send({
uuid: event.uuid,
message: `Echo: ${event.message}`
});
}
});
WebsocketServer.addListener('onClose', (event) => {
console.log('Client disconnected:', event.uuid);
console.log('Code:', event.code, 'Reason:', event.reason);
});
WebsocketServer.addListener('onFailure', (event) => {
console.error('Server failed:', event.reason);
});
// Start the server
async function startServer() {
try {
const result = await WebsocketServer.start({
port: 8080,
// Optional: restrict origins
// origins: ['http://localhost:3000'],
// Optional: specify supported protocols
// protocols: ['chat', 'json'],
// Optional: disable Nagle's algorithm for lower latency
// tcpNoDelay: true
});
console.log(`Server started on ${result.addr}:${result.port}`);
} catch (error) {
console.error('Failed to start server:', error);
}
}
// Stop the server
async function stopServer() {
const result = await WebsocketServer.stop();
console.log(`Server stopped on ${result.addr}:${result.port}`);
}
// Get network interfaces (useful to show the IP address to users)
async function getIpAddresses() {
const interfaces = await WebsocketServer.getInterfaces();
for (const [name, info] of Object.entries(interfaces)) {
console.log(`Interface: ${name}`);
console.log(' IPv4:', info.ipv4Addresses);
console.log(' IPv6:', info.ipv6Addresses);
}
}
// Send binary data
async function sendBinaryData(uuid: string, data: Uint8Array) {
// Convert to base64
const base64 = btoa(String.fromCharCode(...data));
await WebsocketServer.sendBinary({
uuid: uuid,
data: base64
});
}
// Close a specific connection
async function closeConnection(uuid: string) {
await WebsocketServer.close({
uuid: uuid,
code: 1000,
reason: 'Goodbye!'
});
}Platform Notes
Android
The plugin requires the following permissions (automatically added):
INTERNET- Required for WebSocket server to accept connectionsACCESS_WIFI_STATE- Required forgetInterfaces()to enumerate network interfaces
iOS
The plugin uses Apple's Network.framework and requires iOS 15.0 or higher.
Web
WebSocket Server is not available in web browsers as browsers cannot run server-side code. The plugin will throw an error if you try to use it in a web context.
API
start(...)stop()send(...)sendBinary(...)close(...)getInterfaces()addListener('onOpen', ...)addListener('onMessage', ...)addListener('onClose', ...)addListener('onFailure', ...)removeAllListeners()- Interfaces
- Type Aliases
start(...)
start(options: StartOptions) => Promise<ServerInfo>Start the WebSocket server on the specified port.
| Param | Type | Description |
| ------------- | ----------------------------------------------------- | -------------------------------------- |
| options | StartOptions | - Configuration options for the server |
Returns: Promise<ServerInfo>
stop()
stop() => Promise<ServerInfo>Stop the WebSocket server.
Returns: Promise<ServerInfo>
send(...)
send(options: SendOptions) => Promise<void>Send a text message to a specific connection.
| Param | Type | Description |
| ------------- | --------------------------------------------------- | ----------------------------------------- |
| options | SendOptions | - The connection UUID and message to send |
sendBinary(...)
sendBinary(options: SendBinaryOptions) => Promise<void>Send a binary message to a specific connection.
| Param | Type | Description |
| ------------- | --------------------------------------------------------------- | ---------------------------------------------------- |
| options | SendBinaryOptions | - The connection UUID and base64-encoded binary data |
close(...)
close(options: CloseOptions) => Promise<void>Close a specific WebSocket connection.
| Param | Type | Description |
| ------------- | ----------------------------------------------------- | ---------------------------------------------------- |
| options | CloseOptions | - The connection UUID and optional close code/reason |
getInterfaces()
getInterfaces() => Promise<NetworkInterfaces>Get all network interfaces with their IP addresses.
Returns: Promise<NetworkInterfaces>
addListener('onOpen', ...)
addListener(eventName: 'onOpen', listenerFunc: (event: ConnectionOpenEvent) => void) => Promise<PluginListenerHandle>Add a listener for when a new WebSocket connection is opened.
| Param | Type |
| ------------------ | --------------------------------------------------------------------------------------- |
| eventName | 'onOpen' |
| listenerFunc | (event: ConnectionOpenEvent) => void |
Returns: Promise<PluginListenerHandle>
addListener('onMessage', ...)
addListener(eventName: 'onMessage', listenerFunc: (event: MessageEvent) => void) => Promise<PluginListenerHandle>Add a listener for when a message is received from a client.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------- |
| eventName | 'onMessage' |
| listenerFunc | (event: MessageEvent) => void |
Returns: Promise<PluginListenerHandle>
addListener('onClose', ...)
addListener(eventName: 'onClose', listenerFunc: (event: ConnectionCloseEvent) => void) => Promise<PluginListenerHandle>Add a listener for when a WebSocket connection is closed.
| Param | Type |
| ------------------ | ----------------------------------------------------------------------------------------- |
| eventName | 'onClose' |
| listenerFunc | (event: ConnectionCloseEvent) => void |
Returns: Promise<PluginListenerHandle>
addListener('onFailure', ...)
addListener(eventName: 'onFailure', listenerFunc: (event: ServerFailureEvent) => void) => Promise<PluginListenerHandle>Add a listener for when the server fails.
| Param | Type |
| ------------------ | ------------------------------------------------------------------------------------- |
| eventName | 'onFailure' |
| listenerFunc | (event: ServerFailureEvent) => void |
Returns: Promise<PluginListenerHandle>
removeAllListeners()
removeAllListeners() => Promise<void>Remove all listeners for this plugin.
Interfaces
ServerInfo
| Prop | Type | Description |
| ---------- | ------------------- | ------------------------------------------------------- |
| addr | string | The address the server is bound to (usually "0.0.0.0"). |
| port | number | The port number the server is listening on. |
StartOptions
| Prop | Type | Description |
| ---------------- | --------------------- | --------------------------------------------------------------------------------------------------------- |
| port | number | The port number to start the server on. Use 0 to let the system assign an available port. |
| origins | string[] | Optional list of allowed origins for CORS validation. If not specified, all origins are allowed. |
| protocols | string[] | Optional list of WebSocket sub-protocols supported by the server. |
| tcpNoDelay | boolean | Optional flag to enable TCP_NODELAY (disables Nagle's algorithm). Can improve latency for small messages. |
SendOptions
| Prop | Type | Description |
| ------------- | ------------------- | -------------------------------------------------- |
| uuid | string | The UUID of the connection to send the message to. |
| message | string | The text message to send. |
SendBinaryOptions
| Prop | Type | Description |
| ---------- | ------------------- | -------------------------------------------------- |
| uuid | string | The UUID of the connection to send the message to. |
| data | string | The binary data encoded as a base64 string. |
CloseOptions
| Prop | Type | Description |
| ------------ | ------------------- | ------------------------------------- |
| uuid | string | The UUID of the connection to close. |
| code | number | Optional WebSocket close code. |
| reason | string | Optional reason string for the close. |
NetworkInterfaces
PluginListenerHandle
| Prop | Type |
| ------------ | ----------------------------------------- |
| remove | () => Promise<void> |
ConnectionOpenEvent
| Prop | Type | Description |
| ---------------- | ------------------------------------------------- | ------------------------------- |
| connection | Connection | The connection that was opened. |
Connection
| Prop | Type | Description |
| ---------------------- | --------------------------------------------------------------- | -------------------------------------------------------- |
| uuid | string | Unique identifier for this connection. |
| remoteAddr | string | Remote address of the connected client. |
| httpFields | Record<string, string> | HTTP headers from the WebSocket handshake request. |
| resource | string | The resource path requested (URL path and query string). |
| acceptedProtocol | string | The accepted WebSocket protocol (if any). |
| state | 'open' | 'closed' | Current state of the connection. |
MessageEvent
| Prop | Type | Description |
| -------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| uuid | string | The UUID of the connection that sent the message. |
| message | string | The message content. For text messages, this is the string content. For binary messages, this is the base64-encoded data. |
| isBinary | boolean | Whether the message is binary data (base64 encoded). |
ConnectionCloseEvent
| Prop | Type | Description |
| -------------- | -------------------- | ------------------------------------------- |
| uuid | string | The UUID of the connection that was closed. |
| code | number | The WebSocket close code. |
| reason | string | The reason for closing (if provided). |
| wasClean | boolean | Whether the connection was closed cleanly. |
ServerFailureEvent
| Prop | Type | Description |
| ------------ | ------------------- | ------------------------------------- |
| addr | string | The address the server was bound to. |
| port | number | The port the server was listening on. |
| reason | string | The reason for the failure. |
Type Aliases
Record
Construct a type with a set of properties K of type T
{ [P in K]: T; }
