Private Chat Using Node js and socket.io with encrypt and decrypt message and insert into mongo db
node.js and socket.io chat tutorial
This is a very simple single-room chat client using node.js, socket.io and the express module.
i found that the ready availability of documentation and the eagerness of experienced individuals to help the newly adopting, throughout the node.js communities, allow for quicker learning and sharing of acquired skills
UPDATE: long overdue, but you can now skip the following step and just install via the .msi or .pkg files and they
include NPM – http://nodejs.org/#download
to begin, you must install node.js and npm along with their dependencies in Linux System
now, install the modules
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
For Update
sudo apt-get purge node-express
now, install the modules
npm install -d
let’s now create the server file, server.js
var express
= require('express');
var app =
express();
var server
= require('http').createServer(app);
io = require('socket.io').listen(server);
var crypto
= require('crypto');
var mongo =
require("mongojs");
var db =
mongo("database_name", ["table nam"]);
var
response,algorithm = 'aes256';
server.listen(8081);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
console.log("server running");
});
io.sockets.on('connection', function (socket) {
socket.on('register', function (name,
email, password) {
try {
if (name == '') {
response
= {
"success": "0"
, data:
{
"msg": "please enter name"
}
}
socket.emit("register_error", response);
}
else if (email == '') {
response
= {
"success": "0"
, data:
{
"msg": "Please enter emailid"
}
}
socket.emit("register_error", response);
}
else if (password == '') {
response
= {
"success": "0"
, data:
{
"msg": "Please enter Password"
}
}
socket.emit("register_error", response);
}
else {
db.users.find({
email:
email
}, function (err, users) {
if (err) {
response = {
"success": "0"
,
data: {
"msg": "error in singn up"
}
}
socket.emit("register_error", response);
}
else {
if (users.length == 0) {
var newuser = ({
name: name
,
email: email
,
password: password
,
datetime: new Date()
});
db.users.insert(newuser, function (err, result) {
if (err) {
response = {
"success": "0",
data: {
"msg": "Error In Insert user Data"
}
}
socket.emit("register_error", response)
}
else {
response = {
"success": "1"
, data: [result]
}
socket.emit("register_detail", response);
socket.nickname = result._id;
user[socket.nickname] = socket;
}
});
}
else {
response = {
"success": "0"
,
data: {
"msg": "This email Id is already Taken Please
Login"
}
}
socket.emit("register_error", response);
}
}
});
}
}
catch (err) {
response =
{
"success": "0"
, data: {
"msg": "Error Handle in Catch"
}
}
socket.emit("register_error", response);
}
});
socket.on('send_message', function (sender, receiver, message, hash)
{
try {
var delivery;
// Conveert id to mongo db object
id
var sender_id = new mongo.ObjectID(sender);
var receiver_id = new mongo.ObjectID(receiver);
if (!user[receiver]) {
delivery = "0";
}
else {
delivery = "1";
}
if (!user[sender]) {
socket.nickname = sender;
user[socket.nickname] = socket;
}
var encrypt_message = encryptdata(message, hash);
var msg = ({
sender: sender_id
,
receiver: receiver_id
,
msg: encrypt_message
,
msgtype: "0"
,
datetime: new Date()
,
lastupdated: new Date().getTime()
,
isdeliver: delivery
,
isread: "0"
});
db.Chat.insert(msg, function (err, result) {
if (err) {
response = {
"success": "0"
,
data: {
"msg": "Error In Insert Message" + err
}
}
socket.emit('send_message_error', response)
}
else {
var decrypt_message = decryptdata(result.msg, hash)
response = {
"success": "1"
,
data: [{
"_id": result._id
, "sender": result.sender
, "receiver": result.receiver
, "msg": decrypt_message
, "msgtype": result.msgtype
, "isdeliver": result.isdeliver
, "isread": result.isread
}]
}
// send response to sender only
user[sender].emit('send_message_detail', response);
if (user[receiver]) {
// Check reciver is online or
not
user[receiver].emit('send_message_reciver', response);
// if receiver is online send
response to reciver only else not
}
}
})
}
catch (err) {
response
= {
"success": "0"
, data:
{
"msg": "Error Handle in Catch" + err
}
}
socket.emit("send_message_error", response);
}
})
socket.on('disconnect', function (data) {
if (!socket.nickname) return;
delete user[socket.nickname];
// remove user to global array
});
function
encryptdata(msg, key) {
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(msg, 'utf8', 'hex')
+
cipher.final('hex');
return encrypted;
}
function decryptdata(hash, key) {
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(hash, 'utf8', 'hex')
+
decipher.final('utf8');
return decrypted;
}
});
This is a very simple single-room chat client using node.js, socket.io and the express module.
i found that the ready availability of documentation and the eagerness of experienced individuals to help the newly adopting, throughout the node.js communities, allow for quicker learning and sharing of acquired skills
UPDATE: long overdue, but you can now skip the following step and just install via the .msi or .pkg files and they
include NPM – http://nodejs.org/#download
include NPM – http://nodejs.org/#download
to begin, you must install node.js and npm along with their dependencies in Linux System
now, install the modules
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y nodejs
For Update
sudo apt-get purge node-express
now, install the modules
npm install -d
var express
= require('express');
var app =
express();
var server
= require('http').createServer(app);
io = require('socket.io').listen(server);
var crypto
= require('crypto');
var mongo =
require("mongojs");
var db =
mongo("database_name", ["table nam"]);
var
response,algorithm = 'aes256';
server.listen(8081);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
console.log("server running");
});
io.sockets.on('connection', function (socket) {
socket.on('register', function (name,
email, password) {
try {
if (name == '') {
response
= {
"success": "0"
, data:
{
"msg": "please enter name"
}
}
socket.emit("register_error", response);
}
else if (email == '') {
response
= {
"success": "0"
, data:
{
"msg": "Please enter emailid"
}
}
socket.emit("register_error", response);
}
else if (password == '') {
response
= {
"success": "0"
, data:
{
"msg": "Please enter Password"
}
}
socket.emit("register_error", response);
}
else {
db.users.find({
email:
email
}, function (err, users) {
if (err) {
response = {
"success": "0"
,
data: {
"msg": "error in singn up"
}
}
socket.emit("register_error", response);
}
else {
if (users.length == 0) {
var newuser = ({
name: name
,
email: email
,
password: password
,
datetime: new Date()
});
db.users.insert(newuser, function (err, result) {
if (err) {
response = {
"success": "0",
data: {
"msg": "Error In Insert user Data"
}
}
socket.emit("register_error", response)
}
else {
response = {
"success": "1"
, data: [result]
}
socket.emit("register_detail", response);
socket.nickname = result._id;
user[socket.nickname] = socket;
}
});
}
else {
response = {
"success": "0"
,
data: {
"msg": "This email Id is already Taken Please
Login"
}
}
socket.emit("register_error", response);
}
}
});
}
}
catch (err) {
response =
{
"success": "0"
, data: {
"msg": "Error Handle in Catch"
}
}
socket.emit("register_error", response);
}
});
socket.on('send_message', function (sender, receiver, message, hash)
{
try {
var delivery;
// Conveert id to mongo db object
id
var sender_id = new mongo.ObjectID(sender);
var receiver_id = new mongo.ObjectID(receiver);
if (!user[receiver]) {
delivery = "0";
}
else {
delivery = "1";
}
if (!user[sender]) {
socket.nickname = sender;
user[socket.nickname] = socket;
}
var encrypt_message = encryptdata(message, hash);
var msg = ({
sender: sender_id
,
receiver: receiver_id
,
msg: encrypt_message
,
msgtype: "0"
,
datetime: new Date()
,
lastupdated: new Date().getTime()
,
isdeliver: delivery
,
isread: "0"
});
db.Chat.insert(msg, function (err, result) {
if (err) {
response = {
"success": "0"
,
data: {
"msg": "Error In Insert Message" + err
}
}
socket.emit('send_message_error', response)
}
else {
var decrypt_message = decryptdata(result.msg, hash)
response = {
"success": "1"
,
data: [{
"_id": result._id
, "sender": result.sender
, "receiver": result.receiver
, "msg": decrypt_message
, "msgtype": result.msgtype
, "isdeliver": result.isdeliver
, "isread": result.isread
}]
}
// send response to sender only
user[sender].emit('send_message_detail', response);
if (user[receiver]) {
// Check reciver is online or
not
user[receiver].emit('send_message_reciver', response);
// if receiver is online send
response to reciver only else not
}
}
})
}
catch (err) {
response
= {
"success": "0"
, data:
{
"msg": "Error Handle in Catch" + err
}
}
socket.emit("send_message_error", response);
}
})
socket.on('disconnect', function (data) {
if (!socket.nickname) return;
delete user[socket.nickname];
// remove user to global array
});
function
encryptdata(msg, key) {
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(msg, 'utf8', 'hex')
+
cipher.final('hex');
return encrypted;
}
function decryptdata(hash, key) {
var decipher = crypto.createDecipher(algorithm, key);
var decrypted = decipher.update(hash, 'utf8', 'hex')
+
decipher.final('utf8');
return decrypted;
}
});
now, let’s create the client file, index.html
<script src="http://code.Jquery.com/jquery-latest.min.js"></script>
<script src="socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
var totaluser = [];
Array.prototype.remove
= function () {
var what, a = arguments
, L = a.length
, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what))
!== -1) {
this.splice(ax, 1);
}
}
return this;
};
function Register() {
$('#userWrap').show();
$('#nickwrape').hide();
}
jQuery(function ($) {
var $nickForm = $('#setNick');
var $users = $('#users');
var $messageForm = $('#send_message');
var $messagebox = $('#message');
var $chat = $('#chat');
var $userdata = $('#userdata');
var $uname = $('#uname');
var $mobile = $('#mobile');
var $usr = $('#user');
$userdata.submit(function (e) {
e.preventDefault();
socket.emit('register', $uname.val(), $mobile.val()))
$uname.val('');
$mobile.val('');
});
socket.on('register_error', function (data) {
$usr.html(data);
})
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send_message', messagebox.val(),totaluser.toString(),
function (data) {
$chat.append('<span
class="error">' + data + '</span><br/>');
});
$messagebox.val('');
});
});
</script>
run the server
node app.js
Comments
Post a Comment