So you want to set up a web socket server, but you don’t know how. Maybe you just landed here after a bunch of Google searches. Well, keep reading: you’re in the right place.
The Web Socket in a nutshell
The new protocol is revolutionizing the whole Internet.
The Web Socket protocol is the new alternative to the very popular HTTP protocol. The logic of the latter is well known: the client requests, the server responds. Request, response. Stop. This is what we call a simplex connection. It worked for decades, but has severe limitations therefore it’s not ideal for rich web applications, which would work better under a persistent connection. We need to serve content in real time; that’s why the new protocol is born.
The WebSocket is awesome, especially if your goal is to build a chat, a VoIP server, or even a RTS game! Sounds good, huh? Let’s see how it works.
Roll your own Web Socket server and client
This guide is focused on the official W3C’s WebSocket API specification for the client part; we’ll use a Node.js WebSocket implementation as the server. If you’re curious on how Node.js works, just check it out: there are tons of resources out there.
Okay, let’s get started with the client: nothing fussy, It’s just a simple HTML page. Call it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
You may have noticed the
ws_client.js and write:
If you’re already familiar with object-oriented programming, you should know we have been built a new instance of the
WebSocket object, that’s built-in in all modern browsers. The
ws://localhost:1337 part just tells the WebSocket API to initialize a new connection on
localhost:1337 using the
Now let’s code some event handlers. I won’t elaborate, they’re self-descriptive:
1 2 3 4 5 6 7 8 9 10 11 12
Since we want to send a message to the server, we should use the
WebSocket.send() function; but it doesn’t have a callback return value, so I’ll define a new function,
sendMessage(), that does exactly the same plus logging the message on the console.
1 2 3 4
Finally I get the button to work by attaching an event handler to it:
1 2 3 4 5 6
Basically, when we click on the button we send a message to the server. That’s it. You may wonder what does
ev.preventDefault() do; it just makes sure that when we click the Send button, the form doesn’t get submitted.
At this stage you should have downloaded and installed Node.js: the procedure is slightly different for every operating system; just make sure to download the right installer.
This shell command should install the WS implementation for Node.js on your machine. Now open the Node installation folder (if you don’t know where it is and you’re using a UNIX-based operating system, try
which node) and create the file that will host our server:
Since this file will be executed by Node itself, it must start with the following:
Require the WS server and the HTTP protocol APIs:
Then you can define the HTTP server itself:
1 2 3 4 5
The server must be listening on a port. I’ve chosen the
1337 port, but it can be almost anything.
1 2 3
Our WebSocket server is based on the HTTP server we have just created above, with a bit of security rules:
1 2 3 4
autoAcceptConnections parameter is absolutely necessary here, because we don’t want to allow connections from any source domain! That’s why I wrote a custom function that accepts or discards an incoming remote connection: it accepts only requests from
http://localhost, but you can of course allow any origin you want.
1 2 3 4 5 6 7 8
This way we can easily filter connections based on the origin:
1 2 3 4 5
How can we check if a client sends us a message? We can do it by using the
1 2 3
The message must be in UTF-8 format; we must inspect the
message.type attribute. If the type is correct, we can process the request and define the response accordingly. Here’s my demonstrative implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
It’s always a good idea to log when the connection starts and gets closed:
1 2 3 4 5 6 7
And that’s all. We now have a basic WebSocket server implementation and we’re ready for the handshake.
Establish a connection between server and client
We can now test our brand new WebSocket server. Open the command prompt and start the server with:
Finally open the client (index.html) with your favourite browser and try to send a message.
When you send a web socket request as a client, you’ll send an HTTP header like this one:
1 2 3 4 5
And the server will respond something like:
1 2 3 4
This means you just established a full-duplex connection between the client and the server. If everything went as expected, the console should say something like:
And from this point every message will be logged on the console. Of course you shouldn’t close the console or the server will go down. If you want to close the connection you can both press Ctrl + C or close the browser’s window.
I hope you enjoyed following this guide. You can read the full source code of this tutorial on GitHub, or download it directly. The demo also comes with a file for testing your actual browser support for the WebSocket API.