
Here’s a simple example of a client-server chat application using Node.js and the Socket.IO library. This example demonstrates the basic structure and functionality of a chat system. Make sure you have Node.js and Socket.IO installed before running the code.
Install Dependencies: Open your terminal and navigate to the project directory. Run the following commands to install the required packages.
npm init -y
npm install express socket.io
Server-side Code (server.js): Create a file named server.js
and add the following code:
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
socket.on('disconnect', () => {
console.log('A user disconnected');
});
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
Client-side Code (index.html): Create an HTML file named index.html
in the same directory and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO Chat</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
const form = document.getElementById('form');
const input = document.getElementById('input');
const messages = document.getElementById('messages');
form.addEventListener('submit', (e) => {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', (msg) => {
const li = document.createElement('li');
li.textContent = msg;
messages.appendChild(li);
});
</script>
</body>
</html>
Run the Application: In your terminal, run the following command to start the server:
node server.js
Open your web browser and navigate to http://localhost:3000
. You can open multiple browser tabs to simulate different users chatting with each other.
This example provides a basic framework for a real-time chat application using Socket.IO. You can further enhance and customize it by adding user authentication, room support, message timestamps, and more advanced features.