Using ws to create 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
- Start by creating a directory named
websocket-server
containing two files—one namedclient.js
and 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 npm module, we also need to initialize our project:
$ npm init --yes
How to do it…
In this recipe, we're going to create a WebSocket server and a client and send messages between the two...