WebSockets provide a powerful way to enable bidirectional communication between the client and the server. This means, unlike HTTP communication, the server can also initiate communication with the client without explicitly waiting for a request. This feature makes it perfect for use in applications that require real-time data updates such as chat applications, realtime games, analytic trackers, etc.
Here’s a simplified example of how to use it in node.js.
1. First we need to install WebSocket module by running `npm install ws` in the terminal.
1. Now let’s create a simple WebSocket server:
```
const WebSocket = require(‘ws’);
// Create a new WebSocket Server
const server = new WebSocket.Server({ port: 8080 });
// Connection event. This will be emitted when a client connects
server.on(‘connection’, (socket) => {
console.log(‘Client connected’);
1. Now, let’s create a simple WebSocket client.
```
const WebSocket = require(‘ws’);
// Connect to WebSocket server
const socket = new WebSocket(‘ws://localhost:8080’);
socket.on(‘open’, function() { console.log(‘Connected to server’);
// Send a message to the server socket.send(‘Hello from Client!’); });// Listen for messages from the server
socket.on(‘message’, function(message) {
console.log(‘Received: ‘ + message);
});
```
In this example:
- A connection is made to the WebSocket server when a new ‘WebSocket’ object is created with the `new WebSocket(url)` syntax.
- The ‘message’ event listener is set up to respond to any messages that come from the server.
- A message is sent to the server on connection by using the `socket.send()` function.