DEV Community

Cover image for Chat App with WebSocket: Socket Connection
Sokhavuth TIN
Sokhavuth TIN

Posted on

Chat App with WebSocket: Socket Connection


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

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

Top comments (0)