publish & subscribe pattern in Node.js, including server side and client side example.
Special Note: react do NOT support "ws" npm package, please try "Socket.io-client" if you want to use react on client side.
Project setup:
npm init -y
npm install expressWebSocket dependency setup: ws
npm install wsIn my index.js file:
const server = require("http").createServer();
const PORT = 8080;Set up websocket connection: reference: ws-server-code-example
const WebSocket = require("ws");
const wss = new WebSocket.Server({ server });
wss.on("connection", function connection(ws, request, client) {
ws.on("message", function message(msg) {
console.log(`Received message ${msg} from user ${client}`);
});
ws.send("something");
ws.on("close", function close() {
console.log("disconnected");
});
});type: a string of "publish" or "subscribe" or "unsubscribe"channel: a topic stringmessage: the data to publish (for now consider string data as simple case)
const data = {
type: "PUBLISH",
message: message,
channel: channel
};message: the data to publish (for now consider string data as simple case)
const data = {
message: message
};Reference: https://expressjs.com/en/starter/static-files.html
Note: here please put all static files inside "public" folder under root directory.
Code Example:
const path = require("path");
app.use("/static", express.static(path.join(__dirname, "public")));Then the valid URL examples are:
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
Reference: Writing WebSocket client applications - MDN
In order to communicate using the WebSocket protocol, you need to create a WebSocket object; this will automatically attempt to open the
webSocket = new WebSocket(url);
As establishing a connection is asynchronous and prone to failure there is
NO guarantee that calling the send() method immediately after creating a WebSocket object will be successful.
We can at least be sure that attempting to send data only takes place once a connection is established by defining an onopen event handler to do the work:
ws.onopen = function (event) {
ws.send("some data");
};ws.onmessage = function (event) {
console.log(event.data);
}
- Step1: start the server
node index.js
- Step2: open the two urls
http://localhost:8080/publish.html http://localhost:8080/subscribe.html - Step3: free to interact on UI, eg: input some text, click button to test
Demo:
