// Websocket world in which only certain users can join
// Demo of Ancient Brain Websockets functionality.
// Click button and it changes colour in all clients.
const color1 = "#ffffcc";
const color2 = "#FFE4E1";
$('body').css( "margin", "20px" );
$('body').css( "padding", "20px" );
document.write ( `
<div id=maindiv>
<h1> Password only Websocket world </h1>
A Websocket World that only certain users can join. <br>
You enter a password. You only join with users who enter the same password (not with all users of the World). <br>
The first user to run the World can enter any password! But other users must know what password they will use.
<p>
Enter password:
<input style='width:25vw;' maxlength='2000' NAME="p" id="p" VALUE='' >
<button onclick='start();' class=ab-normbutton >Start</button>
<p>
<div id=errordiv name=errordiv> </div>
</div> ` );
function start() // user has entered a password
{
var password = jQuery("input#p").val();
password = password.trim();
if ( ! alphanumeric ( password ) )
{
$("#errordiv").html( "<font color=red> <B> Error: Password must be alphanumeric. </b></font> " );
return;
}
// else we have a password, start the socket run with this password
AB.socketStart ( password );
$("#maindiv").html ( `
<h1> Password only Websocket world </h1>
Click button to set background color in all runs that have same password:
<p>
<button onclick="setColor1();" class=ab-largenormbutton > Color 1 </button>
<button onclick="setColor2();" class=ab-largenormbutton > Color 2 </button>
` );
}
function alphanumeric ( str ) // return if string is just alphanumeric
{
var rc = str.match(/^[0-9a-zA-Z]+$/); // start of line "[0-9a-zA-Z]+" end of line
if ( rc ) return true;
else return false;
}
AB.socketUserlist = function ( a ) // when told users I am sharing with
{
console.log ( JSON.stringify ( a, null, ' ' ) );
}
// --- When I click, set the color and send info to server ----------------------------------------------------------------
function setColor1()
{
document.body.style.background = color1;
sendtoServer(color1);
}
function setColor2()
{
document.body.style.background = color2;
sendtoServer(color2);
}
function sendtoServer ( thecolor )
{
var data =
{
color: thecolor
};
AB.socketOut ( data ); // server gets this, and sends the data to all clients running this World with this password
}
// --- When someone else clicks, server will send me a message and I can set the color -------------------------------------
// define what to do when we get incoming data on the socket:
AB.socketIn = function(data)
{
document.body.style.background = data.color;
};