Socket.io is a trending library that allows bidirectional communication between client and server. It allows event-based communication between the client and server with very less code. It works on every platform, a browser with good speed and reliability. Node.JS is the perfect technology for real-time applications like chat applications and expressjs is the most popular web framework in Node.JS.
Create an express application named chatApp
â`
$ express chatApp
create : chatApp
create : chatApp/package.json
create : chatApp/app.js
create : chatApp/public
create : chatApp/public/stylesheets
create : chatApp/public/stylesheets/style.css
create : chatApp/public/images
create : chatApp/routes
create : chatApp/routes/index.js
create : chatApp/routes/users.js
create : chatApp/views
create : chatApp/views/index.jade
create : chatApp/views/layout.jade
create : chatApp/views/error.jade
create : chatApp/bin
create : chatApp/bin/www
create : chatApp/public/javascripts
install dependencies:
$ cd chatApp && npm install
run the app:
$ DEBUG=chatApp ./bin/www
â`
Move to the application folder.
â`
$ cd chatApp/
â`
Just check the files created inside
â`
$ ls
â`
Now we need to install the dependencies. Dependencies are listed in the package.json. The current content of package.json file is
â`
{
ânameâ: âchatAppâ,
âversionâ: â0.0.0â,
âprivateâ: true,
âscriptsâ: {
âstartâ: ânode ./bin/wwwâ
},
âdependenciesâ: {
âexpressâ: â~4.9.0â,
âbody-parserâ: â~1.8.1â,
âcookie-parserâ: â~1.3.3â,
âmorganâ: â~1.3.0â,
âserve-faviconâ: â~2.1.3â,
âdebugâ: â~2.0.0â,
âjadeâ: â~1.6.0â
}
}
â`
To install the dependencies use the following command.
â`
$ npm install
â`
Now if you check the app.js file you can find lots of code. Remove everything and add the following code
var app = require(‘express’)();
var http = require(âhttpâ).Server(app);
http.listen(3000, function(){
console.log(âlistening on port:3000â);
});
Run the application using
â`
$ node app.js
â`
listening on port:3000
Create an index page with the following code and save the file with name index.html
<!DOCTYPE html>
<html>
<head>
<title>Chat App NodeJS+Socketio+ExpressJS</title>
</head>
<body>
Hello world
</body>
</html>
Now in the app.js we need to set the router for the index.html. For this add the following code inside the app.js
app.get(‘/’, function(req, res){
res.sendfile(âindex.htmlâ);
});
$ node app.js
listening on port:3000
Now check the URL http://localhost:3000/
Now we need to install the socket.io. You can install socket.io using the following command
$ npm install –save socket.io
Now check the package.json and you can find that the socket.io is added to it with the version.
{
ânameâ: âchatâ,
âversionâ: â0.0.0â,
âprivateâ: true,
âscriptsâ: {
âstartâ: ânode ./bin/wwwâ
},
âdependenciesâ: {
âbody-parserâ: â~1.8.1â,
âcookie-parserâ: â~1.3.3â,
âdebugâ: â~2.0.0â,
âexpressâ: â~4.9.0â,
âjadeâ: â~1.6.0â,
âmorganâ: â~1.3.0â,
âserve-faviconâ: â~2.1.3â,
âsocket.ioâ: â^1.3.5â
}
}
Add socket.io into HTML code using
<script src=”https://cdn.socket.io/socket.io-1.2.0.js”></script>
and update index.html with the following code
<script type=”text/javascript”>
var socket = io();
</script>
Update app.js with the following code
io.on(‘connection’, function(socket){
console.log(âNew client is connected to the serverâ);
});
Now update index.html with input box and send button
<!DOCTYPE html>
<html>
<head>
<title>Chat App NodeJS+Socketio+ExpressJS</title>
</head>
<body>
<ul id=âmessagesâ></ul>
<form action=ââ>
<input id=âmâ autocomplete=âoffâ /><button>Send</button>
</form>
<script src=âhttps://cdn.socket.io/socket.io-1.2.0.jsâ></script>
<script src=âhttp://code.jquery.com/jquery-1.11.1.jsâ></script>
<script type=âtext/javascriptâ>
var socket = io();
var name = window.prompt(âWhat is your name?â);
socket.emit(âloginâ, name);
$(âformâ).submit(function(){
socket.emit(âsendMsgâ,{by:name, msg: $(â#mâ).val()});
$(â#mâ).val(â);
return false;
});
socket.on(ânewUserâ, function(name){
$(â#messagesâ).append($(â<li>â).text(name +â is onlineâ));
});
socket.on(âgetMsgâ, function(res){
$(â#messagesâ).append($(â<li>â).text(res.by +â: â+res.msg ));
});
</script>
</body>
</html>
Here we are creating a socket connection and emitting the message that the user type in the text box. We are getting the name of the user using the prompt. then sending a login event to server.
Now we need to listen to these events in server and handle them properly. So open the app.js file and update the io.connection function as:
io.on(‘connection’, function(socket){
console.log(âNew client is connected to the serverâ);
//listening to the sendMsg from client.
socket.on(‘sendMsg’, function(msg){
console.log(âmessage: â + msg);
//emiting the getMsg event to all the sockets that is connected.
io.emit(‘getMsg’, msg);
});
//Listening to the login event.
socket.on(“login”,function(name) {
//emitting the newUser event to all the clients
io.emit(‘newUser’, name);
});
});
Now in the command line type the following code. This will run our application
$ node app.js
Now open your browser and go to http://localhost:3000/ and enjoy the chat
Have questions? Contact the app development experts at InApp to learn more.