Websocket is generally used for real-time and bidirectional communications with server side like NodeJs and client side. It enables the client to get real-time data without continuous polling.
What is Websocket?
Websocket is computer communication protocol, providing simultaneous two-way communication channels over a single transmission controll protocol connection.
Installing websocket in nodejs
First install the ‘ws‘ module by running the following command. You should add the ‘express’ module for creating the nodejs server.
npm install ws
npm install express
Creating Websocket server
Creating the server.js file with express and http. Below is explanation about the websocket.
Server side explanation:
- We import the ‘ws’ module and create the websocket server.
- We listen for ‘connection’ event which occur when client connect to the server.
- Inside the ‘connection’ event listener, we handled the incoming message from the clients using the ‘message’ event and we are sending the messages back to the client using ‘ws.send()’
- We also listen for ‘close’ event when client disconnect to the server.
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
app.use(express.static('public'));
wss.on('connection', function connection(ws) {
console.log('A new client connected');
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
ws.send(`You said: ${message}`);
});
ws.on('close', function close() {
console.log('Client disconnected');
});
});
server.listen(8080, function () {
console.log('Server is listening on http://localhost:8080');
});
Client Side Explanation:
- We create a WebSocket instance by passing the server’s URL (
ws://localhost:8080
) to theWebSocket
constructor. - We listen for
'open'
and'message'
events to handle the connection and incoming messages from the server, respectively. - We define a function (
sendMessage()
) to send messages to the server when the user clicks the “Send” button.
<!-- client.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<input type="text" id="messageInput" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<div id="output"></div>
<script>
const socket = new WebSocket('ws://localhost:8080');
// Event listener for when the connection is established
socket.addEventListener('open', function (event) {
console.log('Connected to WebSocket server');
});
// Event listener for messages from the server
socket.addEventListener('message', function (event) {
console.log('Message from server:', event.data);
document.getElementById('output').innerHTML += `<p>${event.data}</p>`;
});
// Function to send a message to the server
function sendMessage() {
const message = document.getElementById('messageInput').value;
socket.send(message);
}
</script>
</body>
</html>
Thank you for connecting with us. Please see other useful NodeJs tutorials, which are below:
How to use AWS SDK in NodeJs? See all operations
Node.js SSL Setup on Aws EC2 in Easy Short Way
How to use Map in JavaScript? See all operations.
JavaScript String Methods With All Complete Examples