Creating a WebSocket server
For this task, we will use the third-party ws
module to create a pure WebSocket server that will receive and respond to WebSocket requests from the browser.
Getting ready
We'll create a new folder for our project that will hold two files: server.js
and client.html
. The client.html
file will provide a basic user interface and connect to the WebSocket server while server.js
supplies the server-side WebSocket functionality and serves up the client.html
file in response to browser requests. We also need to install the ws
module. Once we've changed the directory in our new folder on the command line, we can run the following code:
npm install ws
Note
For more information on the ws
module, refer to https://www.github.com/einaros/ws.
How to do it...
Let's use require
with the ws
module and create our WebSocket server (we'll call this wss
):
var WSServer = require('ws').Server, wss = new WSServer({port:8080});
Now that we have our WebSocket server (wss
) instance, we can listen...