k.net.webSocket
Upgrade current requests to WebSocket and manage intrasite connections
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
Dedicated WebSocket API endpoint; list / get work in HTTP-triggered KScript | Requires an active HttpContext (non-HTTP contexts such as background jobs throw NullReferenceException); clients must connect via ws:// or wss:// | Server-side push notifications and duplex WebSocket connection management |
Handle WebSockets via k.net.webSocket (note the camelCase webSocket): upgrade the current API request with accept(), or look up an active connection with get() to push messages. Clients must connect using ws:// or wss://, otherwise an error is thrown. Note that k.net.webSocket reads HttpContext.RequestServices in its constructor and can only be used within an HTTP request lifecycle (API, Page, or View).
Quick Start
k.api.get("ws", () => {
k.net.webSocket.accept("user_1", (ctx) => {
if (ctx.type === "Text") {
const conn = k.net.webSocket.get("user_1")
if (conn) conn.sendText("echo: " + ctx.text)
}
})
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
accept(id, receive) | Upgrade current request to WebSocket and block until closed | void |
list() | List all registered connection IDs in the current site | string[] |
get(id) | Retrieve a WebSocketConnection by ID for active push | WebSocketConnection | null |
conn.sendText(text[, callback]) | Asynchronously send a text frame and invoke callback when finished | any |
conn.sendBinary(binary[, callback]) | Asynchronously send a binary frame and invoke callback when finished | any |
conn.close([status[, description]]) | Asynchronously close and dispose the WebSocket connection | any |
accept()
Upgrade the current HTTP request to a WebSocket and block the current script until the connection closes. Limits come from the server appsettings.json (WebSocket section, enforced per site; defaults are MaxConnection: 500, MaxReceiveSize: 131072, MaxSendSize: 131072, Timeout: 30):
- Exceeding
MaxConnectionthrows an exception inaccept(). - Receiving a message larger than
MaxReceiveSize(MessageTooBig) or remaining idle forTimeout * 2seconds (EndpointUnavailable) closes the socket without throwing in the script. MaxSendSizeis read from configuration but is not currently enforced on outbound sends.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Connection ID, unique within the site, for get / list |
receive | (ctx: WebSocketContext) => void | Yes | Message callback; both ctx.binary and ctx.text (lazy UTF-8 decode) are populated for any non-empty message, so branch on ctx.type ("Text" or "Binary") |
Returns: void. The script keeps running until the connection closes.
k.api.get("ws", () => {
k.net.webSocket.accept("user_1", (ctx) => {
if (ctx.type === "Text") {
// Handle text frame (ctx.text)
} else if (ctx.type === "Binary") {
// Handle binary frame (ctx.binary)
}
})
})list()
Returns the list of registered connection IDs for the current site.
Parameters: None.
Returns: string[]. Registered connection IDs for the current site.
const ids = k.net.webSocket.list()get()
Get a connection by ID for server-initiated message pushing or closing.
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Connection ID |
Returns: WebSocketConnection | null. Matching connection, or null when absent.
| Method | Description |
|---|---|
sendText(text, callback?) | Asynchronously send text frame and run callback on completion |
sendBinary(bytes, callback?) | Asynchronously send binary frame and run callback on completion |
close(status?, description?) | Asynchronously close and dispose connection |
Asynchronous sends and callback chaining
sendText, sendBinary, and close are asynchronous (returning immediately before network I/O finishes). Never invoke multiple sends or close() synchronously back-to-back on the same connection—doing so triggers concurrent SendAsync exceptions or cancels/disposes the socket before pending sends finish. Chain sequential sends and close() inside callback.
const conn = k.net.webSocket.get("user_1")
if (conn) {
conn.sendText("hello", () => {
conn.sendBinary([1, 2, 3], () => {
conn.close()
})
})
}TypeScript Definitions
interface KWebSocket {
accept(id: string, receive: (p1: WebSocketContext) => void): void;
list(): string[];
get(id: string): WebSocketConnection;
}
interface WebSocketContext {
text: string;
binary: number[];
type: string;
}
interface WebSocketConnection {
close(status?: any, statusDescription?: string): any;
sendBinary(binary: number[], callback?: Function): any;
sendText(text: string, callback?: Function): any;
}