WebSockets support

Annotating a controller with @webSocket decorator turns it into a WebSocket handler. Controller class methods are automatically used as WebSocket events listeners when they are annotated with the following decorators:

Method Handled WebSocket event Context body (context.body)
@onClose close {code, message} Called when the connection is closed. code is defined in the WebSocket specification.
@onConnect connection undefined Called when the connection is established.
@onMessage message {data, flags} Called when data is received. flags is an object with member binary.
@onPing ping {data, flags} Called when a ping is received. flags is an object with member binary.
@onPong pong {data, flags} Called when a pong is received. flags is an object with member binary.

import { controller, webSocket, onConnect, onMessage, onClose } from 'kikwit';

@webSocket
@controller
export class Forum {  
    @onConnect
    join(context) {
        context.send(`Welcome ${context.query.username}!`);
    }   
    @onMessage
    receive(context) {   
        context.send(`You said: ${context.body.data}`);
    }    
    @onClose
    gone(context) {    
        console.log(`${context.query.username} has gone`);
    }      
}

You can use a script similar to the following to call the above WebSocket controller from a web browser


var ws = new WebSocket('ws://HOST[:PORT]/forum?username=mega-mind');
ws.onmessage = function(event) {    
    console.log(event.data);
};
ws.send("I'm bored!");

The following Context methods are available on WebSocket controllers

Context method Description
close([code], [data]) Gracefully closes the connection, after sending a description message.
pause() Pause the client stream.
ping([data], [options], [dontFailWhenClosed]) Sends a ping. data is sent, options is an object with members mask and binary. dontFailWhenClosed indicates whether or not to throw if the connection isn't open.
pong([data], [options], [dontFailWhenClosed]) Sends a pong. data is sent, options is an object with members mask and binary. dontFailWhenClosed indicates whether or not to throw if the connection isn't open.
resume() Resume the client stream
send(data, [options], [callback]) Sends data through the connection. options can be an object with members mask, binary and compress. The optional callback is executed after the send completes.
stream([options], callback) Streams data through calls to a user supplied function. options can be an object with members mask and binary. callback, of the form function (error, send), is executed on successive ticks of which send is function (data, final).
terminate() Immediately shuts down the connection.

Behind the scenes, Kikwit uses the [ws][ws-package-url] package.

results matching ""

    No results matching ""