expressjsHow can I use Express.js and websockets together to create real-time applications?
Express.js and websockets can be used together to create real-time applications. Websockets enable bi-directional communication between the client and the server, allowing for real-time updates in the application. Here is an example of how to use Express.js and websockets together to create a real-time application:
// Create a websocket server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Create Express server
const express = require('express');
const app = express();
// Create websocket handler
wss.on('connection', (ws) => {
ws.on('message', (message) => {
console.log(`Received message => ${message}`);
});
ws.send('Hello from the server!');
});
// Start Express server
app.listen(3000, () => {
console.log('Express server listening on port 3000');
});
Output example
Received message => Hello from the client!
Express server listening on port 3000
The code above creates a websocket server on port 8080 and an Express server on port 3000. It then creates a websocket handler which logs incoming messages from the client and sends a message to the client. Finally, it starts the Express server.
Code explanation
const WebSocket = require('ws');
- This line imports thews
module which allows us to create a websocket server.const wss = new WebSocket.Server({ port: 8080 });
- This line creates a websocket server on port 8080.const express = require('express');
- This line imports theexpress
module which allows us to create an Express server.const app = express();
- This line creates an Express server.wss.on('connection', (ws) => {...});
- This line creates a websocket handler which handles incoming messages from the client and sends messages to the client.app.listen(3000, () => {...});
- This line starts the Express server on port 3000.
Helpful links
More of Expressjs
- How do I use an Express.js logger?
- How do I use adm-zip with Express.js?
- How do I use Zod with Express.js?
- How do I download a zip file using Express.js?
- How can I use an ExpressJS webhook to receive data from an external source?
- How do I manage user roles in Express.js?
- How do I use Express.js to parse YAML files?
- How can I set up unit testing for an Express.js application?
- How do I render a template using Express.js?
- How can I set up the folder structure for an Express.js project?
See more codes...