What we need for this tutorial
- NPM and NodeJS installed
socket.io
andsocket.io-client
module
Setting up our project
I will be creating my server and client on the same project, If you want to deploy your server code to your hosting provider you need to create seperate project.
First, I created a directory named chat-cli
and initialized npm project with npm init -y
.
Now I installed the required modules like socket.io
and socket.io-client
with npm install socket.io socket.io-client
.
I created two files in our project index.js
(contains Client code) and server.js
(contains Server code).
Now let’s dive into more details.
Creating a Socket.io server
We need socket.io server to process all events and send it to our client. So, Let’s create it.
Open your server.js
file and Let’s write some code.
// Created a socket.io server
const io = require("socket.io")();
// This should be a free port on our server.
const PORT = process.env.PORT || 3000;
// Created a empty user object, This will store names of our users.
const users = {};
// Listening for a connection event (This event fires when a client is connected to your server)
io.on("connection", (socket) => {
console.log("New Connection: " + socket.id);
// If user emitted a `new user` event, This callback will be called with his name.
socket.on('new user', (name) => {
// Storing his name
users[socket.id] = name;
// Emitting an event to all users except that user.
socket.broadcast.emit("message", `${name} joined the chat.`)
});
// Listening for a `message` event.
socket.on('message', (text) => {
// Emitting an event to all users except that user.
socket.broadcast.emit("message", `${users[socket.id]}> ${text}`);
});
});
// Starting up server on PORT
io.listen(PORT);
Now our server code is finished.
Creating Client for Server
We need to create client and let it connect to our server.
Open up index.js
file and Let’s write some code.
// IMPORTING `socket.io-client` module
const io = require('socket.io-client');
// Creating client at the server, you need to pass url of your server where you hosted it.
const socket = io("http://localhost:3000");
// IMPORTING readline module to read from console.
const readline = require('readline');
// Creating an interface to get input from our console.
const rl = readline.createInterface({
input: process.stdin,
});
// Getting users name.
console.log("What is your name?");
rl.question("What is your name?", (text) => {
// Sending users name to server
socket.emit('new user', text.trim());
console.log("You joined the chat");
process.stdout.write("> ");
});
// Listening for event `message` from our server (This will fire when server sends `message` event)
socket.on("message", (text) => {
// Erasing Last line
process.stdout.write("\r\x1b[K")
console.log(text);
process.stdout.write("> ");
});
// Prompting user to enter message.
rl.prompt();
// Fires when we input text from user.
rl.on('line', (text) => {
// Sending message to our server.
socket.emit('message', text.trim());
process.stdout.write("> ");
rl.prompt();
});
Our client code is now finished.
How to run
First open up three terminals or cmd in your project directory, Start your server first by typing node server.js
.
Now run two clients you want to chat by typing node index.js
on two terminals or cmd.
If you have done everything correctly, You will be able to chat.