DEV Community

Cover image for Chat App with WebSocket: Message to Server
Sokhavuth TIN
Sokhavuth TIN

Posted on

2

Chat App with WebSocket: Message to Server


GitHub: https://github.com/Sokhavuth/chat
Heroku: https://khmerweb-chat.herokuapp.com/

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>
Enter fullscreen mode Exit fullscreen mode
// 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}`);
});
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay