Ready to watch this entire course?
Become a member and get unlimited access to the entire skills library of over 4,900 courses, including more Developer and personalized recommendations.Start Your Free Trial Now
- View Offline
- 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
Skill Level Intermediate
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.