I am gonna share, how to create simple chat app using socket.io in NodeJS. This app allows multiple clients to connect to a server and send messages to each other in real-time.
To start, you will need to install the socket.io library using npm:
npm install socket.io
Next, you can create a server that listens for connections and broadcasts messages to all connected clients. Here is the code for the server:
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
// Create an express app
const app = express();
// Create an HTTP server
const server = http.createServer(app);
// Bind socket.io to the server
const io = socketIO(server);
// Listen for new connections
io.on('connection', (socket) => {
console.log('New client connected');
// Listen for messages from this client
socket.on('message', (message) => {
console.log(`Received message from client: ${message}`);
// Broadcast the message to all clients
io.emit('message', message);
});
// Disconnect event
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
// Start the server
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
To connect to the server and send messages, you can use the following code in the client:
const socket = io('http://localhost:3000');
// Send a message to the server
socket.emit('message', 'Hello from the client');
// Listen for messages from the server
socket.on('message', (message) => {
console.log(`Received message from server: ${message}`);
});
This is just a basic example, but you can build on top of this to create a more feature-rich chat app. For example, you could add a user list, support for private messages, or a chat history.
Top comments (0)