WebSocket are useful when constantly comminicating with a server and when a fast reaction time is required.
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.SetOnClose( OnSockClose );
}
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" );
}
Methods
The following methods are available on the WebSocket object:
String
Number: integer
function()
wbs.Batch
Batch method calls to be able to set all object's properties at once.
Note that you need to specify each parameter (use “” or null to leave some out)
Inherited methods can be called by appending an underscore to the function name (ie. txt.Batch({ SetBackColor_: [“red”] })
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.