PHV
Phương Hồ Văn

Real-Time Chat with React and Socket.IO

const express = require("express"); const app = express(); const http = require("http"); const server = http.createServer(app); const { Server } = require("socket.io"); const io = new Server(server); app.get("/", (req, res) => { res.sendFile(__dirname + "/index.html"); }); let chatHistory = []; io.on("connection", (socket) => { socket.on("join", ({ userName, userId }) => { socket.userName = userName; socket.userId = userId; // Notify everyone const joinMessage = `${userName} has joined the chat.`; chatHistory.push({ text: joinMessage, sender: "system" }); io.emit("userJoined", joinMessage); // Send chat history to the new user socket.emit("chatHistory", chatHistory); }); socket.on("message", (msg) => { chatHistory.push(msg); // Save message io.emit("message", msg); }); socket.on("leave", ({ userName }) => { const leaveMessage = `${userName} has left the chat.`; chatHistory.push({ text: leaveMessage, sender: "system" }); io.emit("userLeft", leaveMessage); }); }); server.listen(3000, () => { console.log("Listening on port 3000"); });

Prompt
Component Preview

About

Create interactive real-time chat features with React and Socket.IO, enabling seamless communication in your web app.

Share

Last updated 1 month ago