DEV Community

ZDev1Official
ZDev1Official

Posted on

✉ HOW TO MAKE A CHAT APP ✉

Hi, this is a tutorial about how to build a chat app

here is it @Leroy01010

Let's start


1. Libraries

We need socket.io to make a connection from user to a user.
And we need an express server, and also http.

Code:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
Enter fullscreen mode Exit fullscreen mode

2. Socket.io connection

We need some lines of code, to make a websocket connection.

The first block of code is for the username (for the chat app) and then to send: 'Username joined the chat...'

The second block of code is the opposite of the first one.

The third block of code is about the message, when the user sends a message, it will send his message with the username and the date of the message.

The fourth code block (outside of the websocket connection) is the port listen handler.
Code:

io.sockets.on('connection', (socket) => {
  socket.on('username', function(username) {
    socket.username = username;
    io.emit('is_online', '🔵 <i>' + socket.username + ' joined the chat..</i>');
  });

  socket.on('disconnect', (username) => {
    io.emit('is_online', '🔴 <i>' + socket.username + ' lefted the chat..</i>');
  });

  socket.on('chat_message', (message) => {
    let time = new Date();
    io.emit('chat_message',`<i>${time.toLocaleTimeString()}</i><br>` +  '<strong>' + socket.username + '</strong>: ' + message);
  });
});

// Server listen handler
server.listen(8080, ()=>{
    console.log('Connected!');
});
Enter fullscreen mode Exit fullscreen mode

4. Render the HTML file for the chat.

We need to add some lines before the socket connection.
To render the HTML chat app file.

Code:

app.get('/', function(req, res) {
  res.sendFile(__dirname + "/index.html");
});
Enter fullscreen mode Exit fullscreen mode

5. Fill the index.html with code to make a chat app.

We need to use jQuery to make a form for the chat.

Code:

<!DOCTYPE html>
<html>
  <head>
    <title>Chatorzo</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #fff; padding: 3px; position: fixed; bottom: 0; width: 100%; border-color: #000; border-top-style: solid; border-top-width: 1px;}
        form input { border-style: solid; border-width: 1px; padding: 10px; width: 85%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; margin-left: 2%; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="../../socket.io/socket.io.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
  </head>
  <body style="background: grey;">
      <header align="center">
          <h1>Chatorzo</h1>
      </header>
      <br>
      <br>
      <br>
    <ul id="messages"></ul>
    <form action="/" method="POST" id="chatForm">
      <input id="txt" autocomplete="off" autofocus="on" placeholder="Your message" /><button>Send</button>
    </form>
    <script>
            var socket = io.connect('https://chatorzo-2.zdev1.repl.co');
            $('form').submit(function(e){
                e.preventDefault();
                socket.emit('chat_message', $('#txt').val());
                $('#txt').val('');
                return false;
            });
            socket.on('chat_message', function(msg){
                $('#messages').append($('<li>').html(msg));
            });
            socket.on('is_online', function(username) {
                $('#messages').append($('<li>').html(username));
            });
            var username = prompt('Username:');
            socket.emit('username', username);
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

So we basically added some CSS and some javascript (jQuery) to:

  • Make it responsive and beautiful.
  • Connect the socket code to the HTML file.

And that's it

Have a great day!

Source code: https://repl.it/@ZDev1/chatorzo-2

Top comments (2)

Collapse
 
lukasdoesdev profile image
Lukas Does Dev

Awesome tutorial! Really gets me started with socket.io!

Collapse
 
zdev1official profile image
ZDev1Official

Good! Thanks!