Creating a real-time chat app with Socket.io and JavaScript involves both server-side and client-side implementation. Below, I'll guide you through creating a simple chat application using these technologies.
Prerequisites:
- Node.js installed on your machine.
Step 1: Set Up Your Project
- Create a new directory for your project.
mkdir socketio-chat-app
cd socketio-chat-app
- Initialize your project with npm.
npm init -y
- Install necessary dependencies.
npm install express socket.io
Step 2: Create Server-Side Code
Create a file named server.js for the server-side code.
// server.js
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.use(express.static(__dirname + '/public'));
io.on('connection', (socket) => {
console.log('A user connected');
// Listen for chat messages
socket.on('chat message', (msg) => {
io.emit('chat message', msg); // Broadcast the message to all connected clients
});
// Listen for disconnection
socket.on('disconnect', () => {
console.log('User disconnected');
});
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Step 3: Create Client-Side Code
Create a directory named public in your project and inside it, create an HTML file index.html.
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat App</title>
<script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script>
const socket = io();
// Listen for chat messages
socket.on('chat message', (msg) => {
const messages = document.getElementById('messages');
const li = document.createElement('li');
li.textContent = msg;
messages.appendChild(li);
});
// Send chat messages
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const input = document.getElementById('m');
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
</script>
</body>
</html>
Step 4: Run Your Application
Run your server.
node server.js
Visit http://localhost:3000 in your web browser, and you should be able to see the chat application. Open multiple browser tabs to simulate different users and see real-time chat in action.
That's it! You've created a basic real-time chat application using Socket.io and JavaScript. Feel free to enhance it by adding features like user authentication, private messaging, or a better user interface.
Top comments (1)
thanks