![]() |
VOOZH | about |
In a real-time application, the server needs a way to keep track of who is connected and how to communicate with them individually or in groups. Socket.io handles this by assigning each client a unique connection and allowing the server to manage these connections efficiently. User management in Socket.io typically involves the following steps:
socket.id with user data (e.g., username). disconnect event fires. Step 1: Initialize the project using the command
npm initStep 2 : Install the requires dependencies:
npm i cors express nodemon socket.io httpThe updated dependencies in package.json file of backend will look like:
{
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"http": "^0.0.1-security",
"nodemon": "^3.0.1",
"socket.io": "^4.7.2"
}
}
Example: Socket.on listens for a join event emitted by the frontend; the backend then emits a message event to notify that the user joined. It also handles connection, messaging, and user management functions like add, remove, and get users.
Step 1: Install react for frontend using this command in terminal
npx create react-app clientStep 2: After react installed, install dependencies for Project inside client folder.
cd client
npm i query-string react-emoji react-router socket.io-client
The updated dependencies in package.json file of frontend will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"query-string": "^8.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-emoji": "^0.5.0",
"react-router": "^6.17.0",
"react-scripts": "5.0.1",
"socket.io-client": "^4.7.2",
"web-vitals": "^2.1.4"
},
Step 3: Inside App.js, create routes for the pages join page and chat page and import the components for both pages to display on that route.
Filename: App.js
Output: Open the browser and type localhost 3000 to see the application running.