Creating a WebSocket server
The WebSocket protocol enables two-way communication between a browser and a server. WebSockets are commonly leveraged for building real-time web applications, such as instant messaging clients.
In this recipe, we’re going to use the third-party ws module to create a WebSocket server that we can interact with via our browser.
Getting ready
First, we need to prepare our project directory with the necessary files for the recipe.
- Start by creating a directory named
websocket-servercontaining two files – one namedclient.jsand another namedserver.js:$ mkdir websocket-server $ cd websocket-server $ touch client.js $ touch server.js
- Also, for our client, let’s create a public directory containing a file named
index.html:$ mkdir public $ touch public/index.html
- As we will be using a third-party
npmmodule, we also need to initialize our project:$ npm init --yes
How to do it…
In this recipe, we’...