We already know that any socket client can send chat message to socket server. In contrast, socket server can also send back or forward chat message to all  socket clients. This fact is called “broadcasting message” to all socket clients.

 

When socket server broadcasts chat message, socket clients need to define an event handler on “chat message” to receive the message that could be an ES6 object with many key-value pairs.

 

// 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');
    socket.on('chat message', (obj) => {
        io.emit('chat message', obj);
    });
});

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="msg-board"></div>
                <form action="" onSubmit="submitHandler(event)">
                    <input type="text" id="chat-name" 
                    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>
        const socket = io();

        function submitHandler(e){
            e.preventDefault();
            const chatName = document.getElementById('chat-name');
            const input = document.getElementById('input');
            const obj = {
                chatName: chatName.value, 
                message: input.value,
            };

            if (input.value) {
                socket.emit('chat message', obj);
                input.value = '';
            }
        }

        socket.on('chat message', function(obj){
            const msgBoard = document.getElementById('msg-board');
            const element = document.createElement('div');
            const msg = `${obj.chatName}: ${obj.message}`;
            element.textContent = msg;
            msgBoard.appendChild(element);
            window.scrollTo(0, document.body.scrollHeight);
        });
    </script>
  </body>
</html>

 

GitHub: https://github.com/Sokhavuth/chat

Heroku: https://khmerweb-chat.herokuapp.com