Communicating with WebSockets
HTTP was not made for the kind of real-time applications that many developers are creating today. As a result, all sorts of workarounds have been discovered to mimic the idea of bidirectional, uninterrupted communication between servers and clients.
WebSockets don't mimic this behavior; they provide it.
In this recipe, 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
Let's create a new folder called websocket-app
with a server.js
file, plus a folder called public
, containing an index.html
file:
$ mkdir websocket-app $ cd websocket-app $ touch server.js $ mkdir public $ touch public/index.html
We also need to initialize our app as a Node package, and install the ws
module:
$ npm init -y $ npm install --save ws
How to do it...
In server.js
, let's begin by requiring our dependencies:
const http = require('http') const fs = require('fs') const ws = require('ws...