Creating Real-Time Chat with Node.js and Socket.IO

The way that people use internet evolved from static pages to Ajax and now to realtime web supported by standards like WebSockets and WebRTC. Making a real-time application, like chat, became increadibly easy with the help of platforms like Node.js and libraries like Socket.io. In this post we'll see how to create a minimalistic chat application form the scratch. Create a separate folder for your new project and type `npm init` in it. Then, install the required dependencies. For this project we will only need express.js and socket.io: > npm install --save express socket.io Let's start from a minimalistic express application that can serve static files. Create a file called main.js. Here's how my minimal express app looks: const express = require('express'); const http = require('http'); const app = express(); const server = http.createServer(app); app.use(express.static(`${__dirname}/public`)); server.listen(3000, () => console.log('Ready on 0.0.0.0:3000')); Notice that I had to use node.js standard module `http` to create server instead of using Express right away. We will need that `server` object later when we'll initialize socket.io. The folder called `public` is the one to keep our static client-side files. Let's create `index.html` right away. Usually I would separate JavaScript code in a separate file, but for this tutorial, I'll keep it all in one file for the sake of readability and navigation. File Upload
As you see I added some very basic chat controls to this page and placed ` This code simply displays the message that you send through the form back on the page. This chat is not yet connected to server (and of course you will not see any other user's messages this way). Let's add some Socket.IO magic to this project and connect all the chats. First thing to do is to initialise socket.io on server. Add the follwowin code to your `main.js` file as follows: const io = require('socket.io')(server); io.on('connection', (sock) => { sock.emit('msg', 'You are connected'); }); This code accepts connection from the client and sends back an event of type `msg` to everyone who connected. The only thing we need to do now is to connect the client and display the message! Let's edit our client-side HTML code again:

Comments

Add new comment