Building a Simple Chat Application with Node.js and Socket.io
Hello, This tutorial is talking about how to build a chat application using Node.js + Socket.io, I already posted in my Thai blog at Devahoy and now I just translate it to English version here.
All this tutorial is based on Official Tutorial from socket.io website If you got stuck or misunderstand what I wrote you can read official instead 😎
Prerequisite
There are 2 parts of the program.
- Server side is running on Node.js
- Client side is running on user browser.
and socket.io also has 2 important functions:
socket.on(event, callback)
: for receive a message from an event name.socket.emit(event, message)
: for send a message to an event name.
Step 1. Create a project
I initial project with yarn init
or npm init
If you prefer npm instead yarn
{
"name": "simple-chat",
"version": "2.0.0"
}
Install Express, socket.io, pug
yarn add express pug socket.io
Step 2 : Create app.js
Create a file named app.js
, this is main file for running on server.
const express = require('express')
const path = require('path')
const app = express()const APP_PORT = 5555// This is config for render view in `views` folder
// and use pug as template engine
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')app.get('/', (req, res) => {
res.render('index')
})app.listen(APP_PORT, () => {
console.log(`App running on port ${APP_PORT}`)
})
Then create a file index.pug
inside views
folder
h1 Hello World
Now, the structure of our project looks like this:
├── app.js
├── node_modules
│ ├── express
│ ├── pug
│ └── socket.io
├── package.json
└── views
└── index.pug
and now add a script to start a server by edit package.json
{
"scripts": {
"start": "node app.js"
}
}
You can test a server by running
yarn app.js
Open a browser with http://localhost:5555/ and let’s see a message Hello World
Step 3 Update index.pug
Then, created a file main.css
and save to public/css
folder (This is an optional for custom my css style)
body {
font-family: Avenir, Helvetica, Arial, sans-serif;
}form {
margin-top: 12px;
}#chat-messages li {
padding: 12px;
}
After create main.css
you need to setup public static file access by add this before app.get('/)
app.use(express.static('public'))
Now you can see project structure look like this
├── app.js
├── node_modules
│ ├── express
│ ├── pug
│ └── socket.io
├── package.json
├── public
│ └── css
│ └── main.css
└── views
└── index.pug
Start a server again,
yarn start
Step 4 : Integrated with Socket.io
Next step, we need to connect with socket.io, then add socket.io module to app.js
file
for socket.io on a server we install via
yarn
ornpm
but for socket.io on a client we need to use via CDN.
const server = app.listen(APP_PORT, () => {
console.log(`App running on port ${APP_PORT}`)
})const io = require('socket.io').listen(server)
Then added this:
io.on('connection', function(socket) {
console.log('a user connected');
});
To tell a socket to listen an event named connection
script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js')
script.
const socket = io();
And now my app.js
file look like this
then, add snippet code below to index.pug
to load socket.io from CDN
script(src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js')
script.
const socket = io();
and final version ofindex.pug
file is
When you start a server from the terminal, you can see a message a user connected
Step 5 : Send an event to Server
When we use socket.io, we able to send and receive all message we want, we edit file index.pug
by adding socket.emit(event, message)
(Add this to the last line of a file)
var socket = io();
socket.emit('chatter', 'Hello from client');
และไฟล์ app.js
แก้ไขโดยให้ socket ทำการรับ event ที่ชื่อ chatter
ชื่อเดียวกันกับฝั่ง client
Back to the server side, Editapp.js
file for telling a socket.io to wait for event name chatter (the same name as a client side)
io.on('connection', function(socket) {
socket.on('chatter', function(message) {
console.log('message : ' + message);
});
});
Then, edit index.pug
to create a form for send a message with (We use jQuery)
script.
const socket = io();
$('form').submit(function() {
const name = $('#name').val();
const message = $('#message').val(); socket.emit('chatter', `${name} : ${message}`);
$('#message').val('');
return false;
});
Above the code we:
- Submit a form by read a value from variable
name
andmessage
socket.emit('chatter', value)
is a syntax that we send a message with socket.io- After form submitted, we reset a form value.
Step 6 : Broadcasting
Broadcasting is a step that a server to send a message to all client with a specific event name, Assuming we named client1
- The message sent from
client1
to a server - The Server sends back all message to a client only event name e.g.
io.emit('eventName', 'message'
- All client will be received a message via event name by implement method
io.on('event', callback)
Then in a file app.js
We add io.emit()
with
io.on('connection', (socket) => {
socket.on('chatter', (message) => {
console.log('message : ', message)
io.emit('chatter', message)
})
})
So after the server has received a message, the server sends back to a client with io.emit()
The on a client side index.pug
We need to add this to receive a message from a server (When we received a message we append
to a list
script.
socket.on('chatter', function(message) {
$('#chat-messages').append($('<li>').text(message));
});
Finally, we have a chat application!