×

Real time connection


In this article, we will discuss the things like how to start an npm server, how to use Socket.Io library to connect with ports and how to send messages?

Index.js

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

server.listen(port, () => {
    console.log('Server is running on port ${port}');
});

As you see in the given code, the app is a handler function which is being passed to HTTP server which socket.io requires as a parameter and that HTTP server listens on port 3000.

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.get here tells the server to look at index.html when it starts. Socket.Io provides many events which are used to connect, disconnect, send messages and many more.

io.on('connection', (socket) => {
    console.log('user connected');
    socket.emit('message', { manish: 'hey how are you neha?'});
    socket.on('chat event', (data) => {
        console.log(data);
    })
})

Here, connection event tells the socket that the user is now connected and emit is used to send message "Hey how are you?" to user . Whenever client replies message with chat event then socket.on will listen on chat event to understand that user had sent some message with same chat event, so show them on console log.

Final Index.js

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;

server.listen(port, () => {
    console.log('Server is running on port ${port}');
});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', (socket) => {
    console.log('user connected');
    socket.emit('message', { manish: 'hey how are you neha?'});
    socket.on('chat event', (data) => {
        console.log(data);
    })
})

First socket emits a message when it gets connected. Then, when a user sends a message using form submit actions takes input from text input using jquery .val() method and blanks the user input. Now, socket listens to that sent message and append on the user interface using li tag one by one.

In simple words, user types index.html on browser

Connection gets established on port 3000. Control goes to index.js where we had written server code. Index.js listens connection using io.on('connection') and displays "user connected message" and emits a message to a user How are you? Then when user sends message "I am great thank you" using , socket.on('chat event') in index.js listens that event and put it on console log.


Final Index.html


<html>
<body>
    <!DOCTYPE html>
<html lang="en">
  <head>
    <title>Chatter</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <style>
      form { padding: 20px; position: fixed; bottom: 0; width: 50%; }
      #messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
      #messages li { padding: 5px 10px; }
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <ul id="messagesListen"></ul>
      </div>
      <div class="row">
          <div class="col-lg-6">
            <form action="">
              <div class="input-group">
                  <input id="messageInput" autocomplete="off" type="text" class="form-control" placeholder="Enter a Message here..." aria-label="Message...">
                  <span class="input-group-btn">
                    <button class="btn btn-secondary" type="submit" style="background-color: teal;">Send</button>
                  </span>
                </div>
            </form>
          </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      const socket = io();
      $('form').submit(() => {
        socket.emit('message', $('#messageInput').val());
        $('#messageInput').val('');
        return false;
      });

      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('message', 'user connected');
      })

      socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>
</body>
</html>

index.html which we created inside public folder is used which client users will see.


<html>
<body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
     
      socket.on('connect', () => {
        // emiting to everybody
        socket.emit('message', 'user connected');
      })

      const socket = io();
      $('form').submit(() => {
        socket.emit('message', $('#messageInput').val());
        $('#messageInput').val('');
        return false;
      });

       socket.on('message', (msg) => {
        $('#messagesListen').append($('<li>').text(msg));
      })
    </script>
  </body>
</html>
</body>
</html>


Time to run the application

Open terminal in VS code editor, and place this command to start the server

npm run start

Open browser and type

http://localhost:3000/

In the next tutorial, we will cover how you can create private chat rooms for different communities. It makes sense by the way. See you in the next tutorial.




❮ Previous Next ❯