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" );
}
from native import app
def OnStart():
global txt, serv
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()
sock = app.CreateWebSocket("sock1", ip, 8080)
sock.SetOnOpen(OnSockOpen)
sock.SetOnClose(OnSockClose)
def OnSockOpen():
app.ShowPopup("Connected")
clients = serv.GetWebSockClients()
for i in clients:
txt.Log(clients[i].id + ": " + clients[i].remoteAddress)
def OnSockClose():
app.ShowPopup("Disconnected")
Properties
The following properties are available on the WebSocket object:
Methods
The following methods are available on the WebSocket object:
all types
String
Number: integer
Object: {
command:
args }
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.data
An object for saving individual extra properties.
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.