Skip to content
codingtube

codingtube

Coding and Programming tutorials

  • javascript
  • React
  • ES6
  • React js
  • coding
  • ffmpeg
  • java
  • programming
  • information
  • coding
  • Privacy Policy
  • Twitter trends
  • Age Calculatore
  • Codingtube Community
  • YouTube Tags Generator
  • About
  • Toggle search form

Node.js to Built chat App using Socket.io

Posted on October 4, 2021October 4, 2021 By christo No Comments on Node.js to Built chat App using Socket.io

Here we going to built real time chat App using Node.js with socket.io and nodemon dependency

Table of Contents

  • Dependencies
  • Socket.IO
  • Nodemon
  • Terminal command to install Nodemon
  • Terminal command to install Socket.io

Dependencies

Socket.IO

Enables real-time bidirectional event-based communication. Socket abstract WebSocket connections. It uses WebSocket for transportation and then fallback to long polling when Websockets fail to establish a connection

Nodemon

A tool that helps develop Node.js applications by automatically restarting the node application when file changes in the directory are detected

VS code editor has been used to create this real time chat app using Node.js and Socket.io dependency

Terminal command to install Nodemon

npm install --save-dev nodemon

Terminal command to install Socket.io

npm install socket.io

Now create Project folder Realchat

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Chat App</title>
  <script defer src="http://localhost:3000/socket.io/socket.io.js"></script>
  <script defer src="script.js"></script>
  <style>
    body {
      padding: 0;
      margin: 0;
      display: flex;
      justify-content: center;
    }

    #message-container {
      width: 80%;
      max-width: 1200px;
    }

    #message-container div {
      background-color: #CCC;
      padding: 5px;
    }

    #message-container div:nth-child(2n) {
      background-color: #FFF;
    }

    #send-container {
      position: fixed;
      padding-bottom: 30px;
      bottom: 0;
      background-color: white;
      max-width: 1200px;
      width: 80%;
      display: flex;
    }

    #message-input {
      flex-grow: 1;
    }
  </style>
</head>
<body>
  <div id="message-container"></div>
  <form id="send-container">
    <input type="text" id="message-input">
    <button type="submit" id="send-button">Send</button>
  </form>
</body>
</html>

app.js

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    } 
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

script.js

const socket = io('http://localhost:3000')
const messageContainer = document.getElementById('message-container')
const messageForm = document.getElementById('send-container')
const messageInput = document.getElementById('message-input')

const name = prompt('What is your name?')
appendMessage('You joined')
socket.emit('new-user', name)

socket.on('chat-message', data => {
  appendMessage(`${data.name}: ${data.message}`)
})

socket.on('user-connected', name => {
  appendMessage(`${name} connected`)
})

socket.on('user-disconnected', name => {
  appendMessage(`${name} disconnected`)
})

messageForm.addEventListener('submit', e => {
  e.preventDefault()
  const message = messageInput.value
  appendMessage(`You: ${message}`)
  socket.emit('send-chat-message', message)
  messageInput.value = ''
})

function appendMessage(message) {
  const messageElement = document.createElement('div')
  messageElement.innerText = message
  messageContainer.append(messageElement)
}

server.js

const io = require("socket.io")(3000, {
    cors: {
      origin: "*",
    },
  });

const users = {}

io.on('connection', socket => {
  socket.on('new-user', name => {
      console.log("name"+name)
    users[socket.id] = name
    socket.broadcast.emit('user-connected', name)
  })
  socket.on('send-chat-message', message => {
    socket.broadcast.emit('chat-message', { message: message, name: users[socket.id] })
  })
  socket.on('disconnect', () => {
    socket.broadcast.emit('user-disconnected', users[socket.id])
    delete users[socket.id]
  })
})

package.json

{
  "name": "realchat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "nodemon": "^2.0.13",
    "socket.io": "^4.2.0"
  },
  "devDependencies": {},
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "author": "",
  "license": "ISC"
}

Terminal command to start real time chat app

Terminal 1 command

nodemon app.js

Terminal 2 command

nodemon server.js

screenshot of chat app in Node.js

codingpoint

For more better understanding watch this video to create real time chat app using node.js

Node.js Tags:node.js chat app, real time chat ap, real time chat app using node.js, socket.io

Post navigation

Previous Post: Multidimensional Array in Java
Next Post: Node.js upload file

Related Posts

What is DIRTy applications in Node.js ? Node.js
Streaming data in Node.js Node.js
Node.js Core Modules Node.js
Node.js upload file Node.js
Importing npm Modules in Node.js Node.js
What is Node.js ? Node.js

Leave a Reply Cancel reply

You must be logged in to post a comment.

Recent Posts

  • Affiliate Marketing Principles
  • The Basics You Need to Know About Affiliate Marketing
  • Affiliate Marketing Options
  • All About Affiliate Marketing
  • Classification of Database Management Systems
  • Three-Tier and n-Tier Architectures
    for Web Applications
  • Two-Tier Client/Server Architectures for DBMSs
  • Basic Client/Server Architectures in DBMS
  • Centralized DBMSs Architecture in DBMS
  • Tools, Application Environments, and Communications Facilities in DBMS

Categories

  • Affiliate marketing (5)
  • Algorithm (43)
  • amp (3)
  • android (223)
  • Android App (8)
  • Android app review (4)
  • android tutorial (60)
  • Artificial intelligence (61)
  • AWS (3)
  • bitcoin (8)
  • blockchain (1)
  • c (5)
  • c language (105)
  • cloud computing (4)
  • coding (4)
  • coding app (4)
  • complex number (1)
  • Computer Graphics (66)
  • data compression (65)
  • data structure (188)
  • DBMS (44)
  • digital marketing (9)
  • distributed systems (11)
  • ffmpeg (26)
  • game (3)
  • html (6)
  • image processing (35)
  • Inequalities (1)
  • information (4)
  • java (212)
  • java network (1)
  • javascript (9)
  • kotlin (4)
  • leetcode (1)
  • math (21)
  • maven (1)
  • mysql (1)
  • Node.js (8)
  • operating system (109)
  • php (310)
  • Principle Of Mathematical Induction (1)
  • programming (6)
  • Python (4)
  • Python data structure (9)
  • React native (1)
  • React.js (22)
  • Redux (1)
  • seo (4)
  • set (12)
  • trigonometry (6)
  • vue.js (35)
  • XML (3)

sitemap

sitemap of videos

sitemap of webstories

sitemap of website

  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy
  • Affiliate marketing
  • Algorithm
  • amp
  • android
  • Android App
  • Android app review
  • android tutorial
  • Artificial intelligence
  • AWS
  • bitcoin
  • blockchain
  • c
  • c language
  • cloud computing
  • coding
  • coding app
  • complex number
  • Computer Graphics
  • data compression
  • data structure
  • DBMS
  • digital marketing
  • distributed systems
  • ffmpeg
  • game
  • html
  • image processing
  • Inequalities
  • information
  • java
  • java network
  • javascript
  • kotlin
  • leetcode
  • math
  • maven
  • mysql
  • Node.js
  • operating system
  • php
  • Principle Of Mathematical Induction
  • programming
  • Python
  • Python data structure
  • React native
  • React.js
  • Redux
  • seo
  • set
  • trigonometry
  • vue.js
  • XML
  • Blog
  • Data compression tutorial - codingpoint
  • How to change mbstring in php 5.6
  • How to diagnose out of memory killed PHP-FPM
  • Introduction to jQuery
  • Privacy

© codingtube.tech