HTML5 Power Workshop
Illustration by John Hersey

Implementing a web sockets server


HTML5 Power Workshop

with Andy Olsen

Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Video: Implementing a web sockets server

In this lesson, we're going to see how to implement a web socket server using node js. I have a sample file here, socketserverws.js, and we're going to examine the code in this file in detail in this lesson. If you want to follow along, you have to have nodejs installed on your machine. The project files folder already has the node js msi file. So just run that on your machine. And it'll install node js on the Program Files folder on your computer. Okay.
please wait ...
Watch the Online Video Course HTML5 Power Workshop
3h 9m Intermediate May 31, 2012

Viewers: in countries Watching now:

In this course, part of his series of titles on HTML5 and CSS3, author and expert Andy Olsen looks at advanced topics like geolocation, mobile development, web sockets, Web SQL, and web workers. You'll also learn how to communicate between pages downloaded from different servers and how to use the new Ajax features in XMLHttpRequest Level 2. After completing this workshop, developers be well equipped to start utilizing the powerful features of HTML5.

Topics include:
  • Using the Communications API
  • Understanding geolocation
  • Getting and watching the current position
  • Using web workers and WebSockets
  • Implementing mobile web user interfaces
  • Managing data in a mobile web application
  • Working offline
  • Using Web SQL
  • Using drag-and-drop
Developer Web video2brain
Andy Olsen

Implementing a web sockets server

In this lesson, we're going to see how to implement a web socket server using node js. I have a sample file here, socketserverws.js, and we're going to examine the code in this file in detail in this lesson. If you want to follow along, you have to have nodejs installed on your machine. The project files folder already has the node js msi file. So just run that on your machine. And it'll install node js on the Program Files folder on your computer. Okay.

So I have this file here. SocketServerws.js. I have it already open in the Editor. So, a few preliminaries before we actually run the example and then look at the code. Node js requires the web socket module to be installed, so you have to run this command from the command prompt first, in order to install Web Sockets on your machine. I've already done that in my machine and it creates a folder called Node Modules. And then another sub folder called Web Socket.

So it's already set up in the Project Files folder. Okay, go back in the code. This is how we run the server. Node, which is the node js engine, and then the name of the server which is socketserverws.js. So I'll type that command in, and then press Enter. So node js is running, and it's running my server code. My server code is now running and listening for connections on port eight eight eight eight. I chose that port number because it's fairly safe. Not many other things run on that port.

To test that it's working, I can open up a browser window and type in that URL. And the way I've implemented the server, if you just give it a (INAUDIBLE) like that, it'll just return a file called index.html just to show that the basic HTTP connections are working. So I'll copy that URL into the clipboard and then go back into my Chrome browser and paste it in here. So this will send a normal HTTP request. And the web server will pick it up and just return index.html. Okay, so the web server is running.

Now we need to look at the code to see what it's doing. So this is the URL that will run a genuine web socket client to take advantage of the asynchronous bidirectional communication capabilities between the client and the server. So enter that URL, into my browser window here. As soon as I open that page it'll attempt to open a web socket connection to the web server so that the client and the server can start communicating over web sockets. So I press Enter. So now we have a connection running between the client and the server. I'll go back into my code.

And show you what's happening. So in node js, the first thing you do, is you create a web socket server, like this, and then, you use the HTTP and the FS models so that we can do some basic HTTP processing and some file handling. So the first part of this code just establishes the raw HTTP connection capabilities for node js. So what you do is you take the HTTP object from the previous three statements and you call the create server function, the create server function will create a normal HTTP server.

Any HTTP request that comes in will then be handled by this function on HTTP request and that's the function we have here on line 32. So this function receives an HTTP request and outputs the URL that was requested. And if the user just requested slash like we did, local host /8888 in that case, it just returns index.html. So this is the code in node js that returns the index html file that we just saw. Any other URL and it just sends back a 404.

So that's a very simple, HTTP server, it'll return index.html. And we started listening here on port eight eight eight eight. So, the server is listening on regular HTTP on that port number. There's no web sockets going on yet, this is just pure HTTP, so the next part of the code shows how the web sockets part works. So, let me show you what's going on here. So, in node.js, the first thing you have to do is create a web socket server object, like I've done here.

And then when you click the Object pass in various construction parameters, first of all you specify the HTTP server property plus the HTTP server object that we created a few lines earlier. So the web socket server will be sitting on top of basic HTTP and then the second property is quite important Auto Accept Connections in a production environment, you really should set out to be false. And that means when the client attempts a web socket connection to the server, it doesn't automatically allow that connection to proceed instead it gives you as a web server author the opportunity to intercept the request in the client and check the origin. In other words, where did the client come from.

Okay, so you really want to check the origin to limit the clients that can connect to you. Okay, so that's my web socket server object. Also we can have any number of clients. So I have available here a whole array of connection objects representing all the clients. And then this statement on line 71 handles web socket requests coming from those clients. So every time there's a request from a client for a web socket connection, it'll call this function here, on ws request.

And that function starts on line 73, so let's take a look at that. So every request that comes in will have an origin and the origin property send from the client browser and identifies the domain where that page was downloaded from, when we check it here, we only allow connections from local host. Now in reality, in the protection environment you might want to have more robust check in here against a variety of allowed domains for example.

But in this example, if the origin is anything other than local host then we open a message to reject the connection attempt in the client. Like this. Request reject. That says, from the service point of view, back to the client, you've attempted to establish a web socket communication with me. I don't like where you've come from, therefore, I'm not going to allow you to communicate with me using web sockets. If it was local host, then we proceed under this code, and in that case, we accept the request.

From the origin. And that returns back a connection object. And the connection object allows us to handle all subsequent communication with that client. So, we push the connection onto a client list, that's my array. Because we want to send data back to all the clients. Every second, we send back a message to every client, to tell each client how many clients are connected at the moment. So, if the connection receives a message from the client, this event handler code will be executed. So, for example, in my client, if I send some text from the client to the server, like so, then it sends a message to the server.

And that's picked up in this code here. The connection receives a message, and this is the event handler for that message. So if the message that came in was text, we'll put a message on the console, so that's my command prompt here. Let's say, this is the text that we've received from the client. And then we also, send data, back to the client, effectively echoing what they sent over.

So if the client sends over, whales, we send back a message that says, server bouncing back message, whales. So if we went back into the browser page, we could see that. Message being received by the client. There we go. That was the message that the client sent back. There. Okay, so back into the code. Maybe, the client has attempted to upload a binary file. So, in that case, we can check for that, and we can output a message indicating how many bytes a client attempted to send.

If it's any other type, not text or binary, then we will just output a console message to say, we don't recognize this type of file. So, that's what happens when the client sends a message to the server. If the client disconnects, then a close event occurs, in other words, the browser has closed the window for example, or the client code has officially closed the socket object. So in that case, we just put the message on the screen to save it. The client is disconnected and we remove the client connection from the array this code here will remove the client's connection from our array of connections. Now the reason why we keep the array of all the connections is because the server every one second, the server sends back a message to the client. Giving it an update, of how many clients that can be connected. So back in the browser window, we have one client at the moment, but if I open up another browser window, with the same URL, and then I'll do the same again. So you can see here the server does know how many clients are connected and every one second it'll send a message to each connected client through the array to say how many clients are currently connected and the current time stamp. So the code that does that.

Is at the bottom of my node js example. On line 120 I set up a timer effectively that goes off every one second, every one second it will send messages from the server. It calls this function and that function is here on line 110. So, in this case, we look through all the clients. And if a client is still connected, we send a message back to the client to say the current time stamp at the server, and the number of clients connected.

So if I go back into the client, and close one of these. And in fact I'll close another one. In that case the connection object has a close event. The close event outputs a message to say that a client has disconnected, and it removes the client from its list of connections. And we see the effect of that in the output window here. It shows that one local host and then another local host have disconnected. So that concludes the lesson. We've seen in node js how you can implement a web socket server, how you can handle messages that gets sent to you.

And how you can handle the close event, and how you can send data back to the client asynchronously whenever you want to.

There are currently no FAQs about HTML5 Power Workshop.

Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed HTML5 Power Workshop.

Return to your organization's learning portal to continue training, or close this page.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.