In this tutorial, we are going to learn about WebSockets, a powerful tool that enables real-time, two-way communication between a client and a server over a single, long-lived connection. This technology is crucial for applications that require instant updates, such as chat apps, live sports updates, or stock market apps.
You will learn:
Prerequisites:
WebSockets provide a persistent connection between a client and a server that both parties can use to start sending data at any time. This is different from the traditional HTTP protocol where the client has to initiate the connection.
We'll use the ws
library to set up a WebSocket server in Node.js. First, navigate to your project directory and run:
npm install ws
Next, create a new JavaScript file, let's call it server.js
, and add the following code:
// Import the WebSocket library
const WebSocket = require('ws');
// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
// When a connection is established
wss.on('connection', (ws) => {
console.log('New client connected');
// When a message is received from the client
ws.on('message', (message) => {
console.log('Received: ' + message);
});
// Send a message to the client
ws.send('Hello from server');
});
Let's create a new client.html
file and add the following code:
<!DOCTYPE html>
<html>
<body>
<script>
// Connect to the WebSocket server
let socket = new WebSocket("ws://localhost:8080");
// When the connection is open, send some data to the server
socket.onopen = function(e) {
alert("[open] Connection established");
socket.send("Hello from client");
};
// When a message is received from the server
socket.onmessage = function(event) {
alert(`[message] Data received from server: ${event.data}`);
};
</script>
</body>
</html>
In both the server and client code, we've used the ws
library and the native WebSocket API respectively to open a connection, send and receive messages.
Here's a breakdown of the server code:
const WebSocket = require('ws');
: Import the WebSocket library.const wss = new WebSocket.Server({ port: 8080 });
: Create a WebSocket server on port 8080.wss.on('connection', (ws) => {...});
: Listen for any incoming connections. When a client connects, the callback function is called with the WebSocket (ws
) representing the connection.ws.on('message', (message) => {...});
: Inside the connection callback, we set up a listener for any messages from the client.ws.send('Hello from server');
: Also inside the connection callback, we send a message to the client.Here's a breakdown of the client code:
let socket = new WebSocket("ws://localhost:8080");
: Connect to the WebSocket server.socket.onopen = function(e) {...};
: When the connection is open, send a message to the server.socket.onmessage = function(event) {...};
: Listen for any messages from the server.In this tutorial, you've learned the basics of working with WebSockets for real-time communication. You've set up a simple WebSocket server in Node.js and connected a client to it. You've also learned how to send and receive messages.
To learn more about WebSockets, check out the WebSocket API documentation and the ws
library documentation.
Remember, the best way to learn is by doing. Good luck and happy coding!