Skip to main content

@rtorcato/browser-common / websockets

websockets

Functions

isWebSocketAvailable()

isWebSocketAvailable(): boolean

Defined in: websockets/index.ts:10

Checks if WebSockets are available in the current browser.

Returns

boolean

True if available, false otherwise.

Example

import { isWebSocketAvailable } from '@rtorcato/browser-common/websockets'
if (isWebSocketAvailable()) connect()

createWebSocket()

createWebSocket(url, protocols?, handlers?): WebSocket

Defined in: websockets/index.ts:28

Creates a new WebSocket connection and attaches event listeners.

Parameters

url

string

The WebSocket server URL.

protocols?

string | string[]

Optional subprotocols.

handlers?

Optional event handlers (open, message, error, close).

onOpen?

(event) => void

onMessage?

(event) => void

onError?

(event) => void

onClose?

(event) => void

Returns

WebSocket

The created WebSocket instance.

Example

import { createWebSocket } from '@rtorcato/browser-common/websockets'
const ws = createWebSocket('wss://example.com', undefined, {
onMessage: (e) => console.log(e.data),
})

sendWebSocketMessage()

sendWebSocketMessage(ws, data): boolean

Defined in: websockets/index.ts:59

Sends a message through a WebSocket if it is open.

Parameters

ws

WebSocket

The WebSocket instance.

data

string | Blob | BufferSource

The data to send.

Returns

boolean

True if sent, false otherwise.

Example

import { sendWebSocketMessage } from '@rtorcato/browser-common/websockets'
sendWebSocketMessage(ws, JSON.stringify({ ping: 1 }))

closeWebSocket()

closeWebSocket(ws, code?, reason?): void

Defined in: websockets/index.ts:78

Closes a WebSocket connection if it is open or connecting.

Parameters

ws

WebSocket

The WebSocket instance.

code?

number

Optional close code.

reason?

string

Optional close reason.

Returns

void

Example

import { closeWebSocket } from '@rtorcato/browser-common/websockets'
closeWebSocket(ws, 1000, 'done')