Socket.IO Node.js Whiteboard Quiz Collaboration Tutorial

Socket.IO Node.js Whiteboard Quiz Collaboration Tutorial

Socket.IO Node.js Whiteboard Quiz Collaboration Tutorial

Yesterday’s Socket.IO Node.js Whiteboard Application Primer Tutorial set us up for using the dynamic duo of …

  • Socket.IO … use of sockets
  • Node.js … local web server

… to collaborate with one HTML(5) canvas element per client on HTTP://localhost:3000 sharing canvas graphical data off each other.

Yesterday was a “no holds barred” share (and collaboration) of each other’s canvas data, but today we add in an existant (but modified for the purpose (though you wouldn’t know visiting PHP Bcmath Primer Tutorial‘s live run using its PHP got_big_numbers.php changed in this way)) Mathematics Quiz Game, whose functionality is totally optional as far as the user is concerned, and which we house at the Socket.IO Node.js created webpage in an HTML iframe element.

If you closely examine today’s tutorial picture contents, or this snippet of index.html code …


<iframe id="quizzer" src="HTTP://localhost:8888/got_big_numbers.php" title="Test your collaborators"></iframe>

… you may immediately see an issue here communicating between that (MAMP PHP web application) and our Socket.IO Node.js client on HTTP://localhost:3000 and yes, this investigation of file reading and writing and Javascript DOM client pre-emptive style code we talk about came to nothing that great, until we stumbled upon this useful webpage, thanks, that put me onto the (admittedly kludgy feeling) solution of using HTTP Cookies to manage the communications, and it worked a treat for this purpose. On a non-local web server, you’d probably have to make other arrangements, perhaps introducing a database (like MongoDB, perhaps) into the equation. Be that as it may, this HTTP Cookie method has a nice feel to it, and we based our cookie GET/SET paradigm on the good code at this useful link, so, thanks for that.

In layperson’s terms the maths quiz functionality works …

  • at the beginning of a Socket.IO Node.js execution (cycle), index.js (the server), in its …

    io.on('connection', onConnection);

    onConnect “connection” event logic (where it establishes functionality for the other relevant events such “disconnect” and “question”) … can io.sockets.emit(“gameon”, { receivers: ‘everyone’}); when there are more than one user logged in (and therefore collaboration makes sense) or io.sockets.emit(“gameoff”, { receivers: ‘everyone’}); otherwise …
  • that is used by main.js at the Socket.IO client to set the HTTP Cookie called “gameon” with a value of “y” (for “gameon”, and setting in play the setTimeout Javascript listener function “keepalookout()”, and which you can squint to see in our tutorial picture) and “n” otherwise …
  • and this same HTTP Cookie “gameon” can be read by our MAMP PHP child web application, which changes its looks accordingly (and also sets in play the setTimeout Javascript listener function “check_for_supervision()” to keep checking), including adding in a new HTML input type=button “Challenge” if the HTTP Cookie “gameon” starts with “y” … and …
  • should a user fill in the two numbers and an operator above this button and then click this “Challenge” button, it sets in play …
  • the MAMP PHP child web application appends to the HTTP Cookie “gameon” information about the maths quiz question the user wants to challenge all other users sharing and collaborating the game with …
  • and back at the main.js of the Socket.IO client this HTTP Cookie “gameon” change is detected by the “keepalookout()” listener (talked about above) which goes about updating its HTTP Cookie “gameon”, and populating the question and answer client HTML elements (keeping the answer to themselves in a Javascript global variable, and awaiting optional user filling in of the HTML input type=number “answer” field), as well as (socket emit) sending …

    socket.emit("question", whatq.split(' ')[eval(-1 + whatq.split(' ').length)]);

    … the message to …
  • the Socket.IO server receives the “question” event and …

    socket.on('question', function(msg){
    io.emit('question', msg);
    });

    emits this same message to all those other collaborators so that at …
  • these other collaborators update their HTTP Cookie “gameon” as well as populating the question and answer client HTML elements (keeping the answer to themselves in a Javascript global variable, and awaiting optional user filling in of the HTML input type=number “answer” field) … which has as part of its design …
  • onblur and onchange event logics trap the user answers that may or may not happen, and client Javascript code checks the answer against that Javascript global variable to update the (relevant user’s) score

The rest of the code looks like …

The PHP Bcmath Primer Tutorial code being the PHP that it is you would also want installed the Apache/PHP/MySQL local web server we love around here called MAMP, and hope that it and Node.js don’t start any fisticuffs at 3am?!


Previous relevant Socket.IO Node.js Whiteboard Application Primer Tutorial is shown below.

Socket.IO Node.js Whiteboard Application Primer Tutorial

Socket.IO Node.js Whiteboard Application Primer Tutorial

We’re building on another great Socket.IO Node.js basis web application project (with package.json) by Damien Arrachequesne (of MIT) on GitHub, thanks, called “Whiteboard”, which is a socket based collaborative web application … downloaded and assembled into place on the MacBook Pro and compiled via …


$ npm i && npm start

… and (re)started via …


$ node index

… as per the usual Node.js way … using an HTML(5) canvas to share the drawing of …

  • scribble based lines in a variety of colours … and we added, today …
  • discrete click/touch lines in a wider variety of colours
  • discrete click/touch rectangles
  • discrete click/touch circles
  • discrete click/touch top left image (via an image URL) placement
  • discrete click/touch top left and bottom right image placement

Of course, where this can have useful implications are for games where, effectively, a single screen is shared and graphically collaborated to, by one or more users.

What’s the go integrating …

  • a new “discrete click/touch” set of functionality … into an existant …
  • scribble based line set of functionality

? Totally in main.js (changed in this way) we added/changed the jQuery Javascript event code as below …


var numbermd = 0, lastwas = 0;
var prevx = 0, prevy = 0;


function onMouseDown(e){
numbermd++;
drawing = true;
lastwas = -1;
if (numbermd > 1) {
if (current.drawmode == 'rectangle') {
drawRectangle(prevx, prevy, e.clientX, e.clientY, current.color, true);
numbermd = 0;
} else if (current.drawmode == 'circle') {
drawCircle(prevx, prevy, e.clientX, e.clientY, current.color, true);
numbermd = 0;
} else if (current.drawmode == 'image2') {
drawImage(prevx, prevy, e.clientX, e.clientY, current.color, true);
numbermd = 0;
} else {
drawLine(prevx, prevy, e.clientX, e.clientY, current.color, true);
numbermd = 1;
}
} else if (current.drawmode == 'image1') {
drawImage(e.clientX, e.clientY, -1, -1, current.color, true);
numbermd = 0;
}

current.x = e.clientX;
current.y = e.clientY;
prevx = current.x;
prevy = current.y;

}

function onMouseUp(e){
if (!drawing) { return; }
if (lastwas != -1) numbermd = 0;
drawing = false;
if (lastwas != -1) drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
lastwas = 0;
}

function onMouseMove(e){
if (!drawing) { return; }
numbermd = 0;
lastwas = 1;

drawLine(current.x, current.y, e.clientX, e.clientY, current.color, true);
current.x = e.clientX;
current.y = e.clientY;
}

Do you see a lot the same with the architecture of yesterday’s Socket.IO Node.js Chat Application Primer Tutorial? They share the use of sockets. They share the collaborative screen sharing approach. They share the idea of a single server process, serving a lot of clients using a local Node web server URL of HTTP://localhost:3000 as well. Once you start identifying similarities in things, you build up thoughts regarding how to construct things, because you’ve “seen” something similar in the past. Various platforms have various strengths, and just because this collaborative screen sharing socket using approach has been great over the last two web applications, in our eyes, don’t think there is only ever one way to do things. Being introduced to alternative ways is not going backwards at any time, as long as you are strong in working out what the client wants, and short of that, with a flexible client, what you are comfortable to use as a development platform, so long as you have sussed out it is a physically possible alternative.

Other code parts were …

You can also see this play out at WordPress 4.1.1’s Socket.IO Node.js Whiteboard Application Primer Tutorial.


Previous relevant Socket.IO Node.js Chat Application Primer Tutorial is shown below.

Socket.IO Node.js Chat Application Primer Tutorial

Socket.IO Node.js Chat Application Primer Tutorial

Network sockets are a powerful communication tool for software developers …

A network socket is an internal endpoint for sending or receiving data at a single node in a computer network. Concretely, it is a representation of this endpoint in networking software (protocol stack), such as an entry in a table (listing communication protocol, destination, status, etc.), and is a form of system resource.

Team that with the brilliant Node.js local web server product (we last talked about with Node.js and Node Local Web Server Primer Tutorial) based real time engine socket.io code, and you can build an application, like today’s chat application very speedily, and reliably … thanks, everybody.

So, today’s chat application …

… started as socket.io‘s “Hello World” “foot in the door” (with that one prerequisite that you should install Node.js (as we did at that tutorial link above some time back)) that gets you places fast, then we recommend delving into their very interesting follow up suggestions, expressed by …

  • Hello World “by the book” (HTTP://localhost:3000 Node.js local web server) package.json and index.js and index.js (remember how Node.js has Javascript client and Javascript server … wow!!!) and index.html … then …
  • after work on Hello World follow up questions index.js (changed in this way) and index.html (changed in this way) … attending to …
    1. Broadcast a message to connected users when someone connects or disconnects … user messages are all prefixed by a user count and they can display a user list on request, as discussed below
    2. Add support for nicknames … we start with a robotic (username) nomenclature (eg. [Chatter_1504844291]) and allow user to change name via a designated field or via “I am cedric popples” type of message
    3. Don’t send the same message to the user that sent it himself. Instead, append the message directly as soon as he presses enter. … user can override this (sensible) functionality by placing themselves into an “(only for [cedric popples])” type of list as required
    4. Add β€œ{user} is typing” functionality … trap the jQuery onkeyup event logic as per $(‘form’).keyup(function(event) { [more code here] });
    5. Show who’s online … we make this a client action required piece of functionality
    6. Add private messaging … we allow for “(only for [cedric popples])” and “(not for [cedric popples])” type lists
    7. Share your improvements! … as linked to above, there is also a feature to adjust the message list’s “odd” element colour via …

      CSS:
      #messages li:nth-child(odd) { background: #eee; }
      jQuery Javascript:
      $('#imyc').change(function(){
      $('#messages li:nth-child(odd)').css('background-color', $('#imyc').val());
      document.getElementById('imyc').style.display='none';
      });
      HTML:
      <input type="color" value="lightgray" id="imyc" style="display:none;" title="Colour of odd messages"></input>

… and eventually the way of socket.io sinks in (the verdict? … it’s great!), and you can see where its role might be in the Full-Stack Developer roles that package these software modules up, and which encourage the use of products like Ansible to manage deployment procedures. But for me the question still is … can Socket.IO put the toaster on and can Node.JS get out the plate while Ansible answers all the client’s difficult questions to end up with that “breakfast before you know you wanted it” project we’ve let slip for the last month … wouldn’t you know it, Vagrant up and walked off with the toast before it got to the client.

This web application design, along with so many other platforms, revolves around the concept of a local web server, and if you want to read about Socket.IO in this context, in relation to others we’ve talked about in this “Hello World” frame of reference, the blog post to visit is Cassini++ WebServer Primer Tutorial.


Previous relevant Node.js and Node Local Web Server Primer Tutorial is shown below.

Node.js and Node Local Web Server Primer Tutorial

Node.js and Node Local Web Server Primer Tutorial

We love PHP for web server work, but readily acknowledge …

  1. PHP is losing out, in popularity terms, to frameworks like Node.js (which we introduce to you today with a “Hello World” tutorial, where you’ll see its Javascript (yes, Javascript), in (server side) action)
  2. Node.js is a framework that has Javascript running on the server side, a pretty powerful scenario

… and so, a great divide in programming (frameworks) is developing. Personally, I like the division of “language” between PHP server code and Javascript client code, but can see the “cuteness” of just thinking “Javascript”, and so, today, we show you a Node.js installation on our MacBook Pro using Mac OS X, though you will see, if you take a skeg at our slideshow that Node.js is very much cross-platform by nature.

If you read this blog, you’ll (hopefully) have seen how fond we PHP’ers are here regarding the …


MAMP local web server on port 8888 supporting PHP and a MySql database on port 8889 on a MacBook Pro Mac OS X using web browsers

… well with Node.js, the scenario is …


Node local web server on port 3000 supporting Javascript (Node.js like) and a MySql database (still) on port 8889 (in our case because we co-exist with MAMP and have MAMP running and access its socket file to make the MySql connection) if co-existing with (running) MAMP or port 3306 (it looks like) if there is no MAMP involved

And so, today, we first show a client “facing” “Hello World” scenario of just showing … “Hello World” … a web application “frontend” if you will.

Then we got a MySql database involved … a web application “backend” if you will … and we hope if you are a regular reader at this blog … even though this blog posting may have “rocked your world” with (Node.js) Javascript getting involved at the server side (though we did warn you with our very first Javascript DOM focused tutorial called JavaScript and the DOM Tutorial?! … it’s taken a while for the “wheel” to turn!) … databases always involve server side code, and so we update the hello_world.js to include showing the results of our MySql query …


SELECT * FROM CIRCLE, POINT WHERE pointid=originid

… linked, “back in the day” with this MySql Stored Procedures Primer Tutorial … and after some dead ends where we didn’t know whether to have MAMP running or not … the slideshow is “warts ‘n all” … we end up finding out that Node/Node.js (Javascript)/MySql can co-exist and be an alternative to our cherished MAMP (local Apache web server)/PHP/MySql “power triplet”. To have a few methods to try things can’t be that bad … huh?! Stay tuned please.

We (almost) leave you with the Open Source links that made the research (culminating in today’s tutorial picture) possible … thanks …

Another player in this realm of thinking is Ruby (on Rails), and with this in mind, take a read of Ruby on Rails Primer Tutorial where port 3000 is used with a local web server arrangement, as well. Finally, if all this “web server” talk interests you as much as us, we’ve been compiling “web server” talk, so to speak into this one Cassini++ WebServer Primer Tutorial blog posting, where Node.js thinking from today has been added … Cassini++ ? … Cassini is the simplest (Windows) local web server we can think of, and we work discussions up from that. That tutorial also mentions Mojito Primer Tutorial which also shows Javascript on both sides of the ledger with Node.js getting involved.

If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.


If this was interesting you may be interested in this too.

This entry was posted in eLearning, Event-Driven Programming, Tutorials and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>