The functioning of chat application is that all sockets need to be connected - one socket is on the server, other sockets is on the client-side or on the browser. Those sockets will be connected with each other when the application starts to run.
When socket on the server is connected with which on the client, an event called “connection” is fired. If an event handler for this event has been created, it will be called, and the client-side socket object will be passed as an argument to the handler.
// index.js
// npm install express
// npm install socket.io
// npm install nodemon
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const path = require('path');
const { Server } = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(port, () => {
console.log(`listening on *${port}`);
});
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Khmer Web Chat</title>
<link rel="stylesheet" href="/base.css" />
<link rel="stylesheet" href="/chat.css" />
<link href="/fonts/setup.css" rel="stylesheet" />
<link href="/logo.png" rel="icon" />
</head>
<body>
<section class="Chat region">
<div class="main">
<div class="title">
<input type="button" value="Leave chat" />
</div>
<div class="outer">
<div id="messages">Chat messages</div>
<form id="form" action="" onSubmit="">
<input type="text" required placeholder="Chat name" />
<input id="input" autocomplete="off" required
placeholder="Type your message here" />
<input type="submit" value="Send" />
</form>
</div>
</div>
<div class="sidebar">
<div class="title">All people</div>
<div class="content">Users</div>
</div>
</section>
<script src="/socket.io/socket.io.js"></script>
<script>
let socket = io();
</script>
</body>
</html>