After a connection was established between socket server and socket client, the latter can send messages to socket server anytime by using emit( ) method with “chat message” event and message object as arguments.

 

To receive message object from client, socket server need to define an event handler on “chat message” event.

 

<!--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 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>
        let 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 = '';
            }
        }
    </script>
  </body>
</html>

 

// 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) => {
        console.log(`message: '${JSON.stringify(obj)}`);
    });
});

server.listen(port, () => {
  console.log(`listening on *${port}`);
});

 

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

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