Guest User

Server

a guest
Apr 24th, 2018
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require('dotenv').config();
  2.  
  3. var app = require('express')();
  4. var server = require('http').Server(app);
  5. var io = require('socket.io')(server);
  6. var mysql = require('mysql');
  7. var Redis = require('ioredis');
  8. var redisClient = Redis.createClient();
  9.  
  10. ///////////////////////////         Mysql Connection        ////////////////////////////////
  11. // var con = mysql.createConnection({
  12. //      host: process.env.DB_HOST,
  13. //      user: process.env.DB_USERNAME,
  14. //      password: process.env.DB_PASSWORD,
  15. //      database: process.env.DB_DATABASE
  16. //  });
  17.  
  18. // con.connect(function(err) {
  19. //   if (err) console.error.bind(console, 'DB Connection Error:');
  20. //   else console.log("DB Connected!");
  21. // });
  22.  
  23. var db_config = {
  24.     host: process.env.DB_HOST,
  25.     user: process.env.DB_USERNAME,
  26.     password: process.env.DB_PASSWORD,
  27.     database: process.env.DB_DATABASE
  28.         };
  29.  
  30. var con;
  31.  
  32. function handleDisconnect() {
  33.  
  34.   con = mysql.createConnection(db_config); // Recreate the connection, since
  35.                                                   // the old one cannot be reused.
  36.  
  37.   con.connect(function(err) {              // The server is either down
  38.         if(err)
  39.             {                                     // or restarting (takes a while sometimes).
  40.                 console.log('error when connecting to db:', err.message);
  41.                 setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
  42.             }
  43.         else
  44.             {
  45.                 console.log("DB Connected!");
  46.             }                                     // to avoid a hot loop, and to allow our node script to
  47.   });                                     // process asynchronous requests in the meantime.
  48.                                      
  49.   con.on('error', function(err) {      
  50.         console.log('db error', err);
  51.         if(err.code === 'PROTOCOL_CONNECTION_LOST')
  52.             { // Connection to the MySQL server is usually
  53.                 handleDisconnect();                         // lost due to either server restart, or a
  54.             }
  55.         else
  56.             {                                      // connnection idle timeout (the wait_timeout
  57.                 console.log("Mysql Error - ",err.message);
  58.                 throw err;                                  // server variable configures this)
  59.             }
  60.   });
  61.  
  62. }
  63.  
  64. handleDisconnect();
  65.  
  66. ///////////////////////////         Mysql Connection        ////////////////////////////////
  67.  
  68. var port_number = process.env.SOCKET_IO_PORT || 8080;
  69.  
  70. server.listen(port_number, function(){
  71.     console.log("Listening on localhost:"+port_number)
  72. });
  73.  
  74. var clients = {};
  75.  
  76. ///////////////////////////////////////         App Chat    //////////////////////////////////////////////////////////
  77.     redisClient.subscribe('message');
  78.     redisClient.on("message", function(channel, data) {
  79.  
  80.         var tempdata = JSON.parse(data)
  81.         //console.log("Sending: " + data);
  82.        
  83.         if(clients[tempdata.receiver_id])
  84.             {
  85.                 io.sockets.connected[clients[tempdata.receiver_id].socket].emit('new-message', tempdata);
  86.             }
  87.         else
  88.             {
  89.                 console.log("User does not exist: " + JSON.stringify(tempdata));
  90.             }
  91.  
  92.     });
  93. ///////////////////////////////////////         App Chat    //////////////////////////////////////////////////////////
  94.  
  95.  
  96. io.on('connect', function (socket) {
  97.  
  98. /////////////////////////////////////////////////////
  99. //////////////////          Add User Event      /////////////////////////////////
  100.     socket.on('add-user', function(data)
  101.         {
  102.             //console.log('data - ',data);
  103.             con.query(`SELECT * FROM users WHERE id = `+data.user_id+` AND blocked='0' AND access_token='`+data.access_token+`' LIMIT 0,1 `, function (error, results, fields)
  104.                     {
  105.  
  106.                         if(error)
  107.                             {
  108.                                 io.sockets.connected[data.socket_id].emit('add-user-auth', {success:0, msg: error.message});
  109.                                 console.log(error.message);
  110.                             }
  111.                         else
  112.                             {
  113.  
  114.                                 if(results.length != 0)
  115.                                     {
  116.                                         // console.log('New User Added - '+JSON.stringify(clients))
  117.                                         clients[data.user_id] =
  118.                                             {
  119.                                                 "socket": data.socket_id
  120.                                             };
  121.  
  122.                                         io.sockets.connected[data.socket_id].emit('add-user-auth', {success:1, msg: 'Connected'});
  123.  
  124.                                         console.log('New User Added - '+results[0].id)
  125.  
  126.                                     }
  127.                                 else
  128.                                     {
  129.                                         io.sockets.connected[data.socket_id].emit('add-user-auth', {success:0, msg: 'Invalid Access token'});
  130.                                         console.log('Wrong Access Token - '+data.user_id);
  131.                                     }
  132.  
  133.                             }
  134.  
  135.                     });
  136.  
  137.         });
  138. //////////////////          Add User Evendt         /////////////////////////////////
  139. /////////////////////////////////////////////////////
  140.  
  141.   //Removing the socket on disconnect
  142.     socket.on('disconnect', function()
  143.         {
  144.  
  145.             for(var id in clients)
  146.                 {
  147.                     if(clients[id].socket === socket.id)
  148.                         {
  149.                             delete clients[id];
  150.                             break;
  151.                         }
  152.                 }
  153.  
  154.             //console.log('Connection Disconnected', JSON.stringify(clients));
  155.             //redisClient.quit();
  156.  
  157.         });
  158.  
  159.  
  160. });
Add Comment
Please, Sign In to add comment