Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions redis-node-socket-chat/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org

root = true

[*]

# Change these settings to your own preference
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true

# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
1 change: 1 addition & 0 deletions redis-node-socket-chat/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
46 changes: 46 additions & 0 deletions redis-node-socket-chat/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Chat App with Redis + Node + Socket.io

This repository contains code for a chat application built using the following web technologies:

- [Redis](https://redis.io/)
- [Node.js](https://nodejs.org/en/)
- [Express.js](http://expressjs.com/)
- [Socket.IO](http://socket.io/)

The original blog post can be found at the following link: [Link_Blog_Here](http://google.com)

The Installation process assumes that you already have the above technologies installed on your machine.

## Install

Give download link here

Navigate to the folder and run:

```
npm install
```

To start the server, you can run:

```
npm start
```

The server should start at port 8080 (default). Navigate to [http://localhost:8080](http://localhost:8080) to see the demo.

Although, before doing that, you might want to flush the DB and start with 0 users.

For that, you can uncomment the line in `index.js` that says `client.flushdb();`

Once that is done, you are ready to go. Remember to restart the server if you intend to make any changes to the code.

You can also use something like [nodemon](https://nodemon.io/) to watch your files and restart the server automatically!

## Additional Info

For the full blog post, check out the following link: https://scalegrid.io/blog/using-redis-with-node-js-and-socket-io/

Check out a hosted version of the demo: https://node-socket-redis-chat.herokuapp.com/

[Start your free 14-day trial](https://console.scalegrid.io/users/register) by creating your first Redis cluster on ScaleGrid! No credit card required.
6 changes: 6 additions & 0 deletions redis-node-socket-chat/creds.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"user": "",
"password": "",
"host": "",
"port": 6379
}
132 changes: 132 additions & 0 deletions redis-node-socket-chat/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var fs = require('fs');
var creds = '';

var redis = require('redis');
var client = '';

// Read credentials from JSON
fs.readFile('creds.json', 'utf-8', function (err, data) {
if (err) throw err;
creds = JSON.parse(data);
client = redis.createClient('redis://' + creds.user + ':' + creds.password + '@' + creds.host + ':' + creds.port);

// Redis Client Ready
client.once('ready', function () {

// Flush Redis DB
// client.flushdb();

// Initialize Chatters
client.get('chat_users', function (err, reply) {
if (reply) {
chatters = JSON.parse(reply);
}
});

// Initialize Messages
client.get('chat_app_messages', function (err, reply) {
if (reply) {
chat_messages = JSON.parse(reply);
}
});
});
});

var port = process.env.PORT || 8080;

// Start the Server
http.listen(port, function () {
console.log('Server Started. Listening on *:' + port);
});

// Store people in chatroom
var chatters = [];

// Store messages in chatroom
var chat_messages = [];

// Express Middleware
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
extended: true
}));

// Render Main HTML file
app.get('/', function (req, res) {
res.sendFile('views/index.html', {
root: __dirname
});
});

// API - Join Chat
app.post('/join', function (req, res) {
var username = req.body.username;
if (chatters.indexOf(username) === -1) {
chatters.push(username);
client.set('chat_users', JSON.stringify(chatters));
res.send({
'chatters': chatters,
'status': 'OK'
});
} else {
res.send({
'status': 'FAILED'
});
}
});

// API - Leave Chat
app.post('/leave', function (req, res) {
var username = req.body.username;
chatters.splice(chatters.indexOf(username), 1);
client.set('chat_users', JSON.stringify(chatters));
res.send({
'status': 'OK'
});
});

// API - Send + Store Message
app.post('/send_message', function (req, res) {
var username = req.body.username;
var message = req.body.message;
chat_messages.push({
'sender': username,
'message': message
});
client.set('chat_app_messages', JSON.stringify(chat_messages));
res.send({
'status': 'OK'
});
});

// API - Get Messages
app.get('/get_messages', function (req, res) {
res.send(chat_messages);
});

// API - Get Chatters
app.get('/get_chatters', function (req, res) {
res.send(chatters);
});

// Socket Connection
// UI Stuff
io.on('connection', function (socket) {

// Fire 'send' event for updating Message list in UI
socket.on('message', function (data) {
io.emit('send', data);
});

// Fire 'count_chatters' for updating Chatter Count in UI
socket.on('update_chatter_count', function (data) {
io.emit('count_chatters', data);
});

});
18 changes: 18 additions & 0 deletions redis-node-socket-chat/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.10.2",
"redis": "^2.6.3",
"socket.io": "^1.7.1"
},
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"engines": {
"node": "4.1.1"
}
}
30 changes: 30 additions & 0 deletions redis-node-socket-chat/public/css/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
.container {
width: 777px;
margin: 0 auto;
}

.messages {
border: 1px solid darkgrey;
border-bottom: none;
width: 781px;
height: 240px;
}

#message {
width: 100%;
background-color: #f9f9f9;
}

.chat {
display: none;
}

.msg {
width: 100%;
}

.user {
float: left;
margin-right: 10px;
font-weight: bold;
}
106 changes: 106 additions & 0 deletions redis-node-socket-chat/public/js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
$(function () {

// test
var socket = io();
var chatter_count;
$.get('/get_chatters', function (response) {
$('.chat-info').text("There are currently " + response.length + " people in the chat room");
chatter_count = response.length; //update chatter count
});
$('#join-chat').click(function () {
var username = $.trim($('#username').val());
$.ajax({
url: '/join',
type: 'POST',
data: {
username: username
},
success: function (response) {
if (response.status == 'OK') { //username doesn't already exists
socket.emit('update_chatter_count', {
'action': 'increase'
});
$('.chat').show();
$('#leave-chat').data('username', username);
$('#send-message').data('username', username);
$.get('/get_messages', function (response) {
if (response.length > 0) {
var message_count = response.length;
var html = '';
for (var x = 0; x < message_count; x++) {
html += "<div class='msg'><div class='user'>" + response[x]['sender'] + "</div><div class='txt'>" + response[x]['message'] + "</div></div>";
}
$('.messages').html(html);
}
});
$('.join-chat').hide(); //hide the container for joining the chat room.
} else if (response.status == 'FAILED') { //username already exists
alert("Sorry but the username already exists, please choose another one");
$('#username').val('').focus();
}
}
});
});
$('#leave-chat').click(function () {
var username = $(this).data('username');
$.ajax({
url: '/leave',
type: 'POST',
dataType: 'json',
data: {
username: username
},
success: function (response) {
if (response.status == 'OK') {
socket.emit('message', {
'username': username,
'message': username + " has left the chat room.."
});
socket.emit('update_chatter_count', {
'action': 'decrease'
});
$('.chat').hide();
$('.join-chat').show();
$('#username').val('');
alert('You have successfully left the chat room');
}
}
});
});
$('#send-message').click(function () {
var username = $(this).data('username');
var message = $.trim($('#message').val());
$.ajax({
url: '/send_message',
type: 'POST',
dataType: 'json',
data: {
'username': username,
'message': message
},
success: function (response) {
if (response.status == 'OK') {
socket.emit('message', {
'username': username,
'message': message
});
$('#message').val('');
}
}
});
});
socket.on('send', function (data) {
var username = data.username;
var message = data.message;
var html = "<div class='msg'><div class='user'>" + username + "</div><div class='txt'>" + message + "</div></div>";
$('.messages').append(html);
});
socket.on('count_chatters', function (data) {
if (data.action == 'increase') {
chatter_count++;
} else {
chatter_count--;
}
$('.chat-info').text("There are currently " + chatter_count + " people in the chat room");
});
});
31 changes: 31 additions & 0 deletions redis-node-socket-chat/views/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node.js + Socket.io + Redis Chat | ScaleGrid</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<h1>Node.js + Socket.io + Redis Chat | ScaleGrid</h1>
<div class="join-chat">
<label for="username">Username:</label>
<input type="text" id="username" name="username"/>
<input type="button" id="join-chat" value="Join Chat"/>
</div>
<br/>
<div class="chat-info"></div>
<br/>
<div class="chat">
<div class="messages"></div>
<textarea name="message" id="message" cols="90" rows="5"
placeholder="Enter your message..."></textarea><br/><br/>
<input type="button" id="send-message" data-username="" value="Send Message">&nbsp;
<input type="button" id="leave-chat" data-username="" value="Leave Chat">
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.6.0/socket.io.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>