Getting Started With Node.js and WebSockets
Let’s make a chat playground
WebSockets are the edgy younger sibling of http. They let you maintain an open connection for real time updates. Let’s make a simple chatroom that just displays messages from users. To keep this short, I won’t go into much besides the implementation, so if you need background info check out this explanation.
Overview
Were going to make a playground that lets 2+ tabs talk to each other in a little chat room.
We’ll use two main files: server.js
and index.html
. We’re going to use an Express server to supply our index.html
file, and we’re going to use the ws
library for our second WebSocket server. Also, we’ll used vanilla JS on the frontend, since WebSockets is available in modern browsers; frameworks like React have nothing to do with it.
Installation
In a terminal, run:
mk websockets
cd websockets
> server.js
> index.html
npm init -y
npm i express ws nodemon
Then add “start”: “nodemon server.js”
to your package.json
scripts.