Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Redis command using :

 "npm install redis --save" 

 

Example 1 chats with redis

app.js

/**
* Chat applications using redis
* private message and redis
*/

var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io')(server),
redis = require('redis'),
redisClient = redis.createClient(),
users = {};
server.listen(3000);


app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (client) {
redisClient.lrange("messages", 0,-1, function (err,messages) {
client.emit('get messages', messages);
});
/*chat.getMessages(20, function (err, docs) {
return client.emit('get messages', docs);
});*/
client.on('new user', function (data, callback) {
if (data in users) {
callback(false);
} else {
console.log(data);
callback(true);
/*redisClient.lrange("messages", 0,-1, function (err,messages) {
client.emit('get messages', messages);
});*/
//chat.getMessages(10, callback);
client.nickname = data;
users[client.nickname] = client;
updateUser();
}
});

function updateUser() {
client.emit('usernames', Object.keys(users));
client.broadcast.emit('usernames', Object.keys(users));
}

client.on('send message', function (data, callback) {
var msg = data.trim();
if (msg.substr(0, 3) === '/w ') {
msg = msg.substring(3);
var ind = msg.indexOf(' ');
if (ind !== -1) {
var name = msg.substring(0, ind);
var msg = msg.substring(ind + 1);
if (name in users) {
users[name].emit('whisper', {msg: msg, nickname: client.nickname});
console.log('whisper');
} else {
callback('Error! Enter a valid user!')
}
} else {
callback('Error! Please enter your message');
}
} else {
redisClient.lpush("messages",{msg: msg, nickname: client.nickname}, function () {
redisClient.ltrim("messages", 0, -1);
client.emit('new message', {msg: msg, nickname: client.nickname});
});
}
});

client.on('disconnect', function (data) {
if (!client.nickname) return;
console.log('users :' + client.nickname + 'has left');
delete users[client.nickname];
updateUser();
});
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Socket.io with private message</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h2>Chats</h2>
</div>
<div id="div-user">
<form class="form-inline" id="form-user">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Your username">
<span class="help-block" id="usernameError"></span>
</div>

<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<div id="wrap" style="display: none">
<div class="row">
<div class="col-md-5">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title" id="panel-title">Chats:</h3>
</div>
<div class="panel-body" id="chats"></div>
</div>
</div>
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Users:</h3>
</div>
<div class="panel-body" id="users"></div>
</div>
</div>
</div>

<div class="row">
<div class="col-md-6">
<form id="form-message" class="form-horizontal" role="form">
<div class="input-group">
<span class="input-group-addon" id="user-addon"></span>
<input type="text" class="form-control" id="message" placeholder="your message">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
</div>
</form>
</div>
</div>

</div>

</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function ($) {
var socket = io.connect('http://localhost:3000'),
$divUser = $("#div-user"),
$chats = $("#chats"),
$users = $("#users"),
$formUser = $("#form-user"),
$username = $("#username"),
$usernameError = $("#usernameError"),
$wrap = $("#wrap"),
$formMessage = $("#form-message"),
$message = $("#message"),
$useraddon = $("#user-addon");

//submit form user
$formUser.submit(function (e) {
e.preventDefault();
socket.emit('new user', $username.val(), function (data) {
if (data) {
$wrap.show();
$divUser.hide();
$useraddon.html($username.val());
} else {
$username.closest("form").addClass("has-error");
$usernameError.html("Error, username already have been taken, please try again");
}
});
});
//wait event on usernames
socket.on('usernames', function (data) {
var html = '';
for (i = 0; i < data.length; i++) {
html += data[i] + "<br />";
}
$users.html(html);
});

socket.on('get messages', function (data) {
for (var i = 0; i < data.length; i++) {
displayMessages(data[i]);
}
});

function displayMessages(data){
$chats.append(data.nickname + ": " + data.msg + "<br />");
}

$formMessage.submit(function (e) {
e.preventDefault();
socket.emit('send message', $message.val(), function (data) {
// your stuff here
});
$message.val('');
});
socket.on('new message', function (data) {
displayMessages(data);
});
socket.on('whisper', function (data) {
displayMessages(data);
});
});
</script>

</body>
</html>

 

Leave a Comment:



digital_ocean