Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and servers. On the another hand we have Node.js a JavaScript runtime built on Chrome’s V8 JavaScript engine. Here, We are going to create a Private Chat Application with Node.js, Socket.IO and AngularJS, Where I used AngularJS on my front-end to handle my server request/services.
Server-Side Program :
var express = require('express'); var app = express(); app.set('port', process.env.PORT || 9000); var server = require('http').Server(app); var io = require('socket.io')(server); var port = app.get('port'); app.use(express.static('public')); server.listen(port, function () { console.log("Server listening on: http://localhost:%s", port); }); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); var usernames = {}; var rooms = []; io.sockets.on('connection', function (socket) { socket.on('adduser', function (data) { var username = data.username; var room = data.room; if (rooms.indexOf(room) != -1) { socket.username = username; socket.room = room; usernames[username] = username; socket.join(room); socket.emit('updatechat', 'SERVER', 'You are connected. Start chatting'); socket.broadcast.to(room).emit('updatechat', 'SERVER', username + ' has connected to this room'); } else { socket.emit('updatechat', 'SERVER', 'Please enter valid code.'); } }); socket.on('createroom', function (data) { var new_room = ("" + Math.random()).substring(2, 7); rooms.push(new_room); data.room = new_room; socket.emit('updatechat', 'SERVER', 'Your room is ready, invite someone using this ID:' + new_room); socket.emit('roomcreated', data); }); socket.on('sendchat', function (data) { io.sockets.in(socket.room).emit('updatechat', socket.username, data); }); socket.on('disconnect', function () { delete usernames[socket.username]; io.sockets.emit('updateusers', usernames); if (socket.username !== undefined) { socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected'); socket.leave(socket.room); } }); });
Client-Side Program :
var app = angular.module('myApp', []); /* Controllers */ app.controller('AppCtrl', function ($scope, socket) { $scope.users = []; $scope.curtrentUser = ''; socket.on('connect', function () { }); socket.on('updatechat', function (username, data) { var user = {}; user.username = username; user.message = data; user.date = new Date().getTime(); user.image = 'http://dummyimage.com/250x250/000/fff&text=' + username.charAt(0).toUpperCase(); $scope.users.push(user); }); socket.on('roomcreated', function (data) { socket.emit('adduser', data); }); $scope.createRoom = function (data) { $scope.curtrentUser = data.username; socket.emit('createroom', data); } $scope.joinRoom = function (data) { $scope.curtrentUser = data.username; socket.emit('adduser', data); } $scope.doPost = function (message) { socket.emit('sendchat', message); } }); /* Services */ app.factory('socket', function ($rootScope) { var socket = io.connect(); return { on: function (eventName, callback) { socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }, emit: function (eventName, data, callback) { socket.emit(eventName, data, function () { var args = arguments; $rootScope.$apply(function () { if (callback) { callback.apply(socket, args); } }); }) } }; });
You can download the source code via GitHub. Downloaded source code can be run/executed with the following commands,
npm install #Install packages dependencies node app #Start the Server/Application
Please leave your valuable comments/suggestions/feedback on below comment box if any.
Thank You !!
very good
Thank You 🙂
could you kindly provide an example of the above for ionic framework.
Rightnow, I am not planning for it !
Please tell one thing how do I get number of people(count) joined in a room.
Create a variable and increment on connect and decrement on disconnect, Similarly you can push user id on array.
Hi,
How can I do one to one chat with existing users. Like users already stored in database. We show list of users. I can then select any of the user and start chatting with him privately.
Use username/id as your room name to send message for particular user
hey siva, can you plzz elaborate this point with an example. how do we get the socket id of other user from room and send msg to it.
Check “adduser” on server side code, You can use your own ID/Reference
Good, Creating a simple chat application, then the following development stack works very nicely together:
Express.js (Node.js)
Redis
Socket.IO
Super ji….
Thank you 🙂
Hello Sir, Chat app is excellent. One more thing, I want to know how we can setup database connectivity so that we can save our messages to database. Any help please Thanks in advance.
Thanks for app 🙂
Hi Raman, You can write your DB query inside the socket listen function. It will save your message on database
Okay Sir, Thank you so much for wonderful code (y) Excellent. Very simple and effective for all platforms.
Thank you very much, Your feedback will help to improve quality of writing.
Hi ,
please help me,I need to create a private chat application and but i did not find any sucess .
please help me if any sample of demo code if you provide me its useful for me .
Thanks
Sanjay
Hi Sanjay,
You can find download link above
Thanks,
Siva
How to integrate this chat into laravel. Have you ever tried?
No, Not Yet !! You can try Stackoverflow – Using PHP with Socket.io
Very Useful one.
Thank you siva sankar
Can you tell me how to hide previous messages and show only recent message.
Hi Siddharth,
You need to handle this on client side.
Thanks,
var room = data.room;
what You are sending in data.. from client sides.
the room value?
An identification/reference value. In this code, I’m sending username.
hi shiva which event we create chat room
Event “createroom”
Why we need to create room intense of send data directly using id .. What its advantage
Hi Vinoth,
Usually, We use socket.join(room) on createroom to join on the socket, Here we are using on adduser and createroom is used to store all active users.
Thanks,
Siva
Hi Siva,
Can you please tell me how to implement one-to-one chat. This will be between 2 users only.
Thanks
Shirish
hi,
how can i change the client side programming in angular6
Kavya, I don’t have any post for angular6 yet.
hey, hi sir I have implemented your code on ionic platform it is working nicely but do you have any idea about how to automate the join function.
You can do at “on connection ” event
can you please give an example for java also i have created socket IO connection with android client.I have implemented private chat using Session Client Id but session id keeps on changing can you please tell me which is the right way for private chat .