Skip to content

WebSocket

@fkn/lib/websocket, from @fkn/lib 0.9.73, exports the platform’s WebSocket class, opened by the proxy on the node your session uses. The proxy is the FKN service that cloud.fetch sends a request through, so the server sees that node’s address and never the person’s. This page covers opening a socket, what it refuses, its limits, and what a dropped connection looks like.

Three lines open a socket and read what the server sends:

app.ts
import {
class WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
} from '@fkn/lib/websocket'
const
const socket: WebSocket
socket
= new
new WebSocket(url: string | URL, protocols?: string | string[]): WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
('wss://example.org/api/updates')
const socket: WebSocket
socket
.
WebSocket.onmessage: Handler<MessageEvent<any>>
onmessage
=
event: MessageEvent<any>
event
=>
var console: Console
console
.
Console.log(...data: any[]): void

The console.log() static method outputs a message to the console.

MDN Reference

log
(
event: MessageEvent<any>
event
.
MessageEvent<any>.data: any

The data read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event.

MDN Reference

data
) // each message the server sends, in order

The class has the platform’s members and fires the platform’s events in the platform’s order. A library that takes a WebSocket class as an option takes this one:

app.ts
const
const Socket: {
new (url: string | URL, protocols?: string | string[]): globalThis.WebSocket;
prototype: globalThis.WebSocket;
readonly CONNECTING: 0;
readonly OPEN: 1;
readonly CLOSING: 2;
readonly CLOSED: 3;
}
Socket
: typeof
module globalThis
globalThis
.
var WebSocket: {
new (url: string | URL, protocols?: string | string[]): globalThis.WebSocket;
prototype: globalThis.WebSocket;
readonly CONNECTING: 0;
readonly OPEN: 1;
readonly CLOSING: 2;
readonly CLOSED: 3;
}

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

MDN Reference

WebSocket
=
class WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
// the type a library asks for when it takes the class

The constructor takes a URL and the subprotocols to offer, as the platform’s does. An http: or https: URL is taken as ws: or wss:. binaryType, send, bufferedAmount and close behave as they do on the platform:

app.ts
const
const socket: WebSocket
socket
= new
new WebSocket(url: string | URL, protocols?: string | string[]): WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
('wss://example.org/api/updates', ['catalog.v1'])
const socket: WebSocket
socket
.
WebSocket.binaryType: BinaryType
binaryType
= 'arraybuffer'
const socket: WebSocket
socket
.
WebSocket.addEventListener<"open">(type: "open", listener: (this: WebSocket, ev: Event) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
addEventListener
('open', () => {
const socket: WebSocket
socket
.
WebSocket.protocol: string
protocol
// 'catalog.v1', the protocol the server chose
const socket: WebSocket
socket
.
WebSocket.send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void
send
(
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

@param ― value A JavaScript value, usually an object or array, to be converted.

@param ― replacer A function that transforms the results.

@param ― space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

@throws ― {TypeError} If a circular reference or a BigInt value is found.

stringify
({
subscribe: string
subscribe
: 'catalog' }))
})
const socket: WebSocket
socket
.
WebSocket.addEventListener<"message">(type: "message", listener: (this: WebSocket, ev: MessageEvent<any>) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
addEventListener
('message',
event: MessageEvent<any>
event
=> {
if (
event: MessageEvent<any>
event
.
MessageEvent<any>.data: any

The data read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event.

MDN Reference

data
=== 'done')
const socket: WebSocket
socket
.
WebSocket.close(code?: number, reason?: string): void
close
(1000, 'done')
})
const socket: WebSocket
socket
.
WebSocket.addEventListener<"close">(type: "close", listener: (this: WebSocket, ev: CloseEvent) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
addEventListener
('close',
event: CloseEvent
event
=> {
event: CloseEvent
event
.
CloseEvent.code: number

The code read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.

MDN Reference

code
// 1000 after the close above
})

A message’s data is a string for a text message, and an ArrayBuffer or a Blob for a binary one, by binaryType. A send copies typed arrays and ArrayBuffers when you call it, and the close goes out after every send before it. extensions is always ''.

In a dedicated worker, the page relays the worker with relayWorker first, as for every entry that reaches the broker. The broker is the connection your app holds into FKN. A worker nobody relayed fails each socket once the broker has not answered within 8,000 ms. See workers.

The constructor throws at once, as the platform’s does, for a scheme other than ws:, wss:, http: and https:, for a URL with a fragment, and for a subprotocol that is not a token or is offered twice. Each is a SyntaxError DOMException. Two refusals are FKN’s own:

app.ts
try {
new
new WebSocket(url: string | URL, protocols?: string | string[]): WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
('wss://fkn.app/')
} catch (
var error: unknown
error
) {
(
var error: unknown
error
as
interface Error
Error
).
Error.message: string
message
// 'websocket refuses FKN platform domains (fkn.app)'
}
try {
new
new WebSocket(url: string | URL, protocols?: string | string[]): WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
('wss://example.org/api/updates', ['fkn-proxy'])
} catch (
var error: unknown
error
) {
(
var error: unknown
error
as
interface DOMException

The DOMException interface represents an abnormal event (called an exception) that occurs as a result of calling a method or accessing a property of a web API.

MDN Reference

DOMException
).
DOMException.name: string

The name read-only property of the one of the strings associated with an error name.

MDN Reference

name
// 'SyntaxError', the library names the target to the proxy in that protocol
}

A host FKN owns is refused with websocket refuses FKN platform domains (<hostname>), and the hosts are listed under platform hosts. The subprotocol fkn-proxy and every one starting fkn-proxy. are refused because the library uses them to carry the target to the proxy.

Once the constructor has returned, a refusal arrives as events. A connection the proxy did not open fires error, then close with code 1006, an empty reason and wasClean false, as the platform reports any failed handshake. The event does not say why, because the platform gives a page no status for a refused handshake.

The proxy refuses a target that resolves to a non-public address, through its egress validation. Its fair-use limits refuse a caller past its request rate, and a target whose origin has used up its shared budget. It also refuses a server that does not answer within 15,000 ms, and a server that chooses none of the subprotocols you offered.

Every connection carries these limits:

LimitValuePast it
a connection4 hoursthe proxy ends it, and close fires with 1006
one frame, either direction4 MiBthe connection ends with 1006
one message, either direction8 MiBthe connection ends with 1006
messages your app has not read16 MiBerror, then close with 1006

A message travels in one frame or in several. Firefox 151 sends a message in one frame, and so do many server libraries, so a message over 4 MiB from them ends the connection. Chromium 149 splits a large send into several frames, so its messages can reach 8 MiB. Keep each message at 4 MiB or under.

The 16 MiB is what the broker holds for your app while your handlers are busy. A server that sends faster than your app reads fills it, and the socket is closed rather than left to queue without bound.

Both directions are paced at the rate of the person’s tier, as a fetch’s response is. What the server sends counts toward the person’s free volume for the day. See account and quota.

Nothing reconnects by itself. A connection that ends without a close handshake fires close with code 1006, an empty reason and wasClean false, and no error, as the platform’s does. A proxy restart, the 4 hour limit and a lost network all look like this.

Open a new socket from a close listener when you need one:

app.ts
const
const connect: () => WebSocket
connect
= ():
class WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
=> {
const
const socket: WebSocket
socket
= new
new WebSocket(url: string | URL, protocols?: string | string[]): WebSocket

The platform's WebSocket, opened by FKN's proxy on the node the session uses: the server sees that node's address, never the person's, and the proxy applies its egress validation, fair-use limits and metering as for a fetch. Its messages pass through the proxy's memory, so it is for servers the browser should not reach from its own address.

It behaves as the platform's, events and their order included, with what the platform also refuses: a url that is not ws:, wss:, http: or https:, a fragment, a protocol that is not a token or is offered twice. It also refuses FKN's own hosts and a protocol named fkn-proxy or starting fkn-proxy., which carry the target to the proxy. Nothing reconnects by itself. A Worker needs relayWorker from its page first; without it the socket fails once the broker has not answered within the deadline of apiWithin. extensions is always empty.

WebSocket
('wss://example.org/api/updates')
const socket: WebSocket
socket
.
WebSocket.addEventListener<"close">(type: "close", listener: (this: WebSocket, ev: CloseEvent) => any, options?: boolean | AddEventListenerOptions): void (+1 overload)
addEventListener
('close',
event: CloseEvent
event
=> {
if (
event: CloseEvent
event
.
CloseEvent.code: number

The code read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.

MDN Reference

code
!== 1000)
function setTimeout<[]>(callback: () => void, delay?: number): NodeJS.Timeout (+1 overload)
setTimeout
(
const connect: () => WebSocket
connect
, 5_000) // 1006 after a drop, so a new socket in 5 s
})
return
const socket: WebSocket
socket
}
const connect: () => WebSocket
connect
()

An open socket holds a busy token, websocket (1) in shell.busyReasons(), from the constructor until its close event. See busy tokens.