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 download a zip file using Express.js?
- What are some of the best alternatives to Express.js for web development?
- How can I use Express.js to generate a zip response?
- How do I set the time zone in Express.js?
- How do I use Zod with Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use express-zip js to zip and download files?
- How can I use Zipkin to trace requests in Express.js?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js and Winston together to create a logging system?
See more codes...