Skip to content

Instantly share code, notes, and snippets.

@kevinchisholm
Last active November 29, 2023 10:25
Show Gist options
  • Save kevinchisholm/dabc35e47906a677eda09b3e6fa87bc6 to your computer and use it in GitHub Desktop.
Save kevinchisholm/dabc35e47906a677eda09b3e6fa87bc6 to your computer and use it in GitHub Desktop.
Code Examples for my Blog Post: Create a Node.js Websocket Server in Five Minutes

Node Logo

Setup

  • Clone this repo:
git clone git@github.com:kevinchisholm/video-code-examples.git
  • Move into the project directory:
cd video-code-examples/node/websocket-basic-server/

(for example: cd ~/Desktop/video-code-examples/node/websocket-basic-server/)

  • Install Dependencies:
npm install

Local Web Server Instructions

Start the local web server:

node index.js

Open the example web page:

http://localhost:3000/
"use strict";
const serverPort = 3000,
http = require("http"),
express = require("express"),
app = express(),
server = http.createServer(app),
WebSocket = require("ws"),
websocketServer = new WebSocket.Server({ server });
//when a websocket connection is established
websocketServer.on('connection', (webSocketClient) => {
//send feedback to the incoming connection
webSocketClient.send('{ "connection" : "ok"}');
//when a message is received
webSocketClient.on('message', (message) => {
//for each websocket client
websocketServer
.clients
.forEach( client => {
//send the client the current message
client.send(`{ "message" : ${message} }`);
});
});
});
//start the web server
server.listen(serverPort, () => {
console.log(`Websocket server started on port ` + serverPort);
});
{
"connection": "ok"
}
"use strict";
const serverPort = 3000, http = require("http"), express = require("express"), app = express(), server = http.createServer(app), WebSocket = require("ws"), websocketServer = new WebSocket.Server({ server });
websocketServer.on('connection', (webSocketClient) => {
webSocketClient.send('{ "connection" : "ok"}');
webSocketClient.on('message', (message) => { websocketServer.clients.forEach( client => { client.send(`{ "message" : ${message} }`) });
});
});
server.listen(serverPort, () => {console.log(`Websocket server started on port ` + serverPort) });
{
"name": "node-express-websockets-basic",
"version": "1.0.0",
"description": "Basic Websockets server using Node.js, Express.js and ws; a Node.js WebSocket library",
"main": "index.js",
"author": "Kevin Chisholm",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"ws": "^4.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment