diff --git a/redis-node-socket-chat/.editorconfig b/redis-node-socket-chat/.editorconfig new file mode 100644 index 0000000..18911a2 --- /dev/null +++ b/redis-node-socket-chat/.editorconfig @@ -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 diff --git a/redis-node-socket-chat/.gitignore b/redis-node-socket-chat/.gitignore new file mode 100644 index 0000000..b512c09 --- /dev/null +++ b/redis-node-socket-chat/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/redis-node-socket-chat/README.md b/redis-node-socket-chat/README.md new file mode 100644 index 0000000..83cc3e3 --- /dev/null +++ b/redis-node-socket-chat/README.md @@ -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. diff --git a/redis-node-socket-chat/creds.json b/redis-node-socket-chat/creds.json new file mode 100644 index 0000000..94445ca --- /dev/null +++ b/redis-node-socket-chat/creds.json @@ -0,0 +1,6 @@ +{ + "user": "", + "password": "", + "host": "", + "port": 6379 +} diff --git a/redis-node-socket-chat/index.js b/redis-node-socket-chat/index.js new file mode 100644 index 0000000..1e46e44 --- /dev/null +++ b/redis-node-socket-chat/index.js @@ -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); + }); + +}); diff --git a/redis-node-socket-chat/package.json b/redis-node-socket-chat/package.json new file mode 100644 index 0000000..1d78f9b --- /dev/null +++ b/redis-node-socket-chat/package.json @@ -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" + } +} diff --git a/redis-node-socket-chat/public/css/main.css b/redis-node-socket-chat/public/css/main.css new file mode 100644 index 0000000..65e3c68 --- /dev/null +++ b/redis-node-socket-chat/public/css/main.css @@ -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; +} diff --git a/redis-node-socket-chat/public/js/main.js b/redis-node-socket-chat/public/js/main.js new file mode 100644 index 0000000..9a976db --- /dev/null +++ b/redis-node-socket-chat/public/js/main.js @@ -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 += "