Here is a little JavaScript object that I am using to maintain reliable (always connected) WebSocket links between multiple Android devices. This code is very useful if you don't know the order in which devices are going to be turned on or if some devices temporarily go missing from the network (it tries to reconnect to remote devices every 7 seconds).
It's designed to connect to a remote device running DroidScript's built-in HTTP server and you can put it in a file called WebSock.js and include into your main App using this line of code:-
function btn_OnTouchDown()
{
sock.Send( "Hello" );
}
Here is the JavaScript object code:-
function WebSock( id, ip, port, options )
{
var m_OnMessage = null;
var m_sock = null;
var m_timer = null;
console.log( "Opening web socket:" + id );
if( !port ) port = 8080;
m_sock = new WebSocket( "ws://"+ip+":"+port );
m_sock.onopen = OnOpen;
m_sock.onmessage = OnMessage;
m_sock.onclose = OnClose;
m_sock.onerror = OnError;
m_timer = setInterval( CheckSocket, 7000 );
function OnOpen() {
console.log( "Socket Open: "+id );
}
function CheckSocket() {
if( m_sock.readyState != 1 ) {
console.log( "Re-opening web socket:" + id );
m_sock = new WebSocket( "ws://"+ip+":"+port );
}
}
function OnClose() { console.log( "Socket Closed: "+id ); }
function OnError(e) { console.log( "Socket Error: "+e.data ); }
function OnMessage( msg ) { if( m_OnMessage ) m_OnMessage( msg.data ); }
this.GetSocket = function() { return m_sock; }
this.SetOnMessage = function( callback ) { m_OnMessage = callback; }
this.Send = function( msg ) {
if( m_sock.readyState != 1 ) console.log( "Socket not ready:"+m_sock );
else m_sock.send( msg );
}
}