Build a chat application with Express and Socket.io

Search for a command to run...

No comments yet. Be the first to comment.
Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...

Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript. https://youtu.be/lKe57l8sttw Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE...

Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless. So, let's get started. Step 1. Create an AWS Account ☁️ In order to deploy functions to AWS Lambda, you should have a...

Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding. So, let's get started. Step...

Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...

Hey guys, In this article, we would be building a real chat application. Building a chat application is really easy.
For this application, we would be using Express.js and Socket.io.
I would recommend you to code along with me to better understand the code.
After then create the following two new folders inside the chatApp folder:
server
client

Now, head over to the server folder and run the following command:
npm init
After initializing package.json lets now install some dependencies
npm install socket.io
const http = require('http');
const socket = require('socket.io');
const server = http.createServer();
const io = socket(server);
server.listen(8080, () => console.log(`Server Running`))
In the above code firstly we required the node’s build-in HTTP module and created a server using createServer() method.
Then, we imported our socket.io and named it as socket which returns a function.
Finally, we initialised our io by calling the function socket and passed our server as parameter to it.
const http = require('http');
const socket = require('socket.io');
const server = http.createServer();
const io = socket(server);
io.on('connection', socket => {
console.log('A new user has joined the chat')
socket.emit('message', 'You have successfully joined the chat')
})
server.listen(8080, () => console.log(`Server Running`))
Whenever there is a new user or a connection joins the chat, the ‘connection’ event is fired by the socket.io, to which we are listening with the .on method.
so io.on(‘connection’), means whenever there is a connection this function will be called. This function has a second argument which is a callback function that has access to a single parameter and that is a socket. The socket contains information about the user who has just joined.
So whenever a new user joins the chat, our server would log A new user has joined the chat. Also, we must welcome the user who has just joined by saying, You have successfully joined the chat.
So, to send a message only to a particular user who has just joined we do:
socket.emit('message', '**You have successfully joined the chat');**
.emit method is used to fire up an event where the first parameter is event name and second is the data.
With that being set now let us set up our listeners for the incoming and outgoing chat messages.
So to listen to an event we use the .on method.
const http = require('http');
const socket = require('socket.io');
const server = http.createServer();
const io = socket(server);
io.on('connection', socket => {
console.log('A new user has joined the chat')
socket.emit('message', 'You have successfully joined the chat')
socket.on('message', (msg) => {
io.emit('message', msg)
})
})
server.listen(8080, () => console.log(`Server Running`))
Let me simplify, In the above code, we are listening to an event named as “message” which would be fired up from our frontend later. So whenever a socket ( which is a user ) sends a message we will take that message and send that to everyone. The io means everyone.
socket.emit — Only to the user. IO — To all the users connected to our application.
Now Run your server:
node index.js
and keep it running…

Now, let's design a simple frontend in index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat App</title>
<style>
.chat-container{
border: 2px solid;
padding: 20px;
height: 500px;
overflow: scroll;
}
</style>
</head>
<body>
<div class="bg-dark text-white p-3 text-center">
<h1>Chat App</h1>
</div>
<div class="container mt-5">
<ul id="chat-box" class="list-group chat-container">
</ul>
<form class="mt-3" id="chat-form">
<input type="text" class="form-control" id="messageBox" required/>
<button type="submit" class="btn btn-success form-control mt-2">Send</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script src="./index.js"></script>
</body>
</html>
Our Design

const form = document.getElementById('chat-form');
const messageBox = document.getElementById('messageBox');
const chatBox = document.getElementById('chat-box')
const socket = io('localhost:8080');
socket.on('message', (msg) => {
const liTag = document.createElement('li');
liTag.classList.add('list-group-item')
liTag.innerText = msg;
chatBox.appendChild(liTag)
})
form.addEventListener('submit', e => {
e.preventDefault();
socket.emit('message', messageBox.value)
messageBox.value = ''
})
So firstly we initialize our socket variable and pass our servers address.
Then, we listen to the message event fired by our backend which contains the message.
server/index.js: Rember this?
And finally, we add an event listener to our form and emits the user message to a socket which is being listened by our backend.
Ohh! I got a welcome Message
Also, my server says that
Authentication in Nodejs using Passport.js In this article I would be teaching you authentication in nodejs using express and passport.jsmedium.com Express and MongoDB In this article, I would be teaching you how to use MongoDB with express.js and perform CRUD operations.medium.com Building REST API with Node.js Build your own REST API from scratchmedium.com Top 10 visual studio code extensions 2020 Best vscode extensions to make your development smooth and powerful.medium.com
Github: https://github.com/piyushgarg195
Linkedin: https://www.linkedin.com/in/piyushgarg195/
Website: https://www.piyushgarg.dev/