top of page

Node.JS Beginnings



This morning's Coffee and Code session consisted of setting up a basic Node.JS server and getting a checkbox to emit its status to all of the connected clients.

Here on GitHub you'll find the results.

I'm using the Socket.IO library to allow for the two-way connection between the client and the server.

One of the main "gotcha's" that I ran into was that the file handler has to be able to send the socket.io.js script to the client. A lot of the example socket.io code just had it serving up the index.html which won't work.


I found this bit of code on StackOverflow, of course, and one thing to make note of is that blindly serving up all files that the client can request isn't really that safe, a client in this case could request any file on your server with the code the way it is. So not recommended to use this for a web-facing server.

One thing I had to tweak was that if the client requests the / page, I need to send the index.html file. So I just set a local variable to that index.html and if it isn't / then I change it to the page that it is looking for.

The other part of the server code is the Socket.IO portion


When the Client connects to the server, first it sends out the current state of our PersistentCheckBoxState.

Then it registers for a callback on the "testCtrl" signal. "testCtrl" is sent from the client side javascript when the checkbox is checked.

It changes the state of our server variable and then does a Broadcast to all other clients that might be listening. This way the checkbox state is maintained across all the browsers that might be looking at the page.

On the client side


There is a listener for when the page is loaded, then it adds a listener for when the state of the checkbox is changed. This is where it emits the "testCtrl" signal that the server is listening for.

Also, the socket is set up to listen for the signal from the server so that it can update its checkbox to the real time data. This connection is what maintains the state across all of the clients.

And so with that, you have the basic skills to create a realtime updating checkbox webpage!

To use the source on Github you'll need node.js and all the socket.io package. I use VisualStudio 2017 which makes it simple in my opinion.

Also I discovered http://hilite.me/ which is what I used to create these cool code blocks.

Comments


bottom of page