Skip to content

k.net.webSocket ​

Upgrade current requests to WebSocket and manage intrasite connections

Execution ContextPrerequisitesTypical Use
Dedicated WebSocket API endpoint; list / get work in HTTP-triggered KScriptRequires 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 ​

js
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 / PropertyDescriptionReturns
accept(id, receive)Upgrade current request to WebSocket and block until closedvoid
list()List all registered connection IDs in the current sitestring[]
get(id)Retrieve a WebSocketConnection by ID for active pushWebSocketConnection | null
conn.sendText(text[, callback])Asynchronously send a text frame and invoke callback when finishedany
conn.sendBinary(binary[, callback])Asynchronously send a binary frame and invoke callback when finishedany
conn.close([status[, description]])Asynchronously close and dispose the WebSocket connectionany

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 MaxConnection throws an exception in accept().
  • Receiving a message larger than MaxReceiveSize (MessageTooBig) or remaining idle for Timeout * 2 seconds (EndpointUnavailable) closes the socket without throwing in the script.
  • MaxSendSize is read from configuration but is not currently enforced on outbound sends.
ParameterTypeRequiredDescription
idstringYesConnection ID, unique within the site, for get / list
receive(ctx: WebSocketContext) => voidYesMessage 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.

js
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.

js
const ids = k.net.webSocket.list()

get() ​

Get a connection by ID for server-initiated message pushing or closing.

ParameterTypeRequiredDescription
idstringYesConnection ID

Returns: WebSocketConnection | null. Matching connection, or null when absent.

MethodDescription
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.

js
const conn = k.net.webSocket.get("user_1")
if (conn) {
  conn.sendText("hello", () => {
    conn.sendBinary([1, 2, 3], () => {
      conn.close()
    })
  })
}

TypeScript Definitions ​

ts
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;
}