Back

CreateWebSocket

Hello World
Content:
- Methods

WebSocket are useful when constantly comminicating with a server and when a fast reaction time is required.

wbs = app.CreateWebSocket( id, ip, port ) → app object: WebSocket

A web socket will automatically open after creating it. Once after finished loading, the OnOpen callback is called.

In order to receive messages from the server you have to specify a OnMessage callback.

See Also: CreateWebServer

Example - Basic

function OnStart()
{
    ip = app.GetIPAddress();

    lay = app.CreateLayout( "linear", "VCenter,FillXY" );

    txt = app.CreateText( "No connected clients.", 0.8, 0.3, "AutoScale,log" );
    txt.SetTextSize( 22 );
    lay.AddChild( txt );

    app.AddLayout( lay );

    serv = app.CreateWebServer( 8080 );
    serv.SetFolder( app.GetAppPath() );
    serv.SetOnReceive( serv_OnReceive );
    serv.Start();

    var sock = app.CreateWebSocket( "sock1", ip, 8080 );
    sock.SetOnOpen( OnSockOpen );
    sock.SetOnError( Sock_OnError );

}

function OnSockOpen()
{
    app.ShowPopup( "Connected" );
    var clients = serv.GetWebSockClients();
    for(var i in clients)
        txt.Log( clients[i].id + ": " + clients[i].remoteAddress );
}

function OnSockClose()
{
    app.ShowPopup( "Disconnected" );
}
    Copy     Copy All       Run      

Methods

The following methods are available on the WebSocket object:

Close()
GetSocket() → object: Javascript Object: Socket
IsOpen() → boolean
string
number: integer
function()
function( message )
wbs.Close
Close the web socket.
wbs.GetSocket
Returns the js Socket instance
wbs.IsOpen
Check whether WebSocket is open
wbs.Send
Send a message to the server
wbs.SetOnClose
Define a callback function which is called when the WebSocket has been closed.
wbs.SetOnMessage
Define a callback function which is called when the WebSocket recived a message from the server.
wbs.SetOnOpen
Define a callback function which is called when the WebSocket has been opened.