javascript - Only Update Specific Users Socket IO and Node JS -
i trying learn node js , attempting extend article.
http://www.gianlucaguarini.com/blog/push-notification-server-streaming-on-a-mysql-database/
i having major issue because getting multiple updates in sql query.
i want send 1 socket update.
this issue in transactions loop multiple socket updates.
i have been struggling on month , can't seem figure out on own (or google searches)
can please tell me how can make work 1 socket update per client.
what happen when there change in 1 of transactions 2 parties (buyer , seller) ones socket update.
how can make work? close want can't on last challenge.
please help.
thank in advance.
<html> <head> <title>gat updater</title> <script src="/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://board.gameassettrading.com/js/jquery.cookie.js"></script> </head> <body> <script> var nodeuserid; function getuserid() { var url = window.location.href; var user_id = url.replace('http://heartbeat.gameassettrading.com:4000/id/', ''); return user_id; } user_id = getuserid(); $.cookie('useridcookie', user_id, { expires: 1 }); var useridcookie = $.cookie("useridcookie"); // base url development between local , dev enviroment function getbaseurl() { var url = location.href; // entire url including querystring - also: window.location.href; var baseurl = url.substring(0, url.indexof('/', 14)); if (baseurl.indexof('http://localhost') != -1) { // base url localhost var url = location.href; // window.location.href; var pathname = location.pathname; // window.location.pathname; var index1 = url.indexof(pathname); var index2 = url.indexof("/", index1 + 1); var baselocalurl = url.substr(0, index2); return baselocalurl + "/"; } else { // root url domain name return baseurl + "/"; } } // set base_url variable base_url = getbaseurl(); document.domain = "transactionsserver.com" // create new websocket var socket = io.connect('http://heartbeat.transactionsserver.com:4000'); socket.on('connect',function() { var data = { url: window.location.href, }; socket.emit('client-data', data); }); // open have filter out data want socket.on('notification', function (data) { if(data.hasownproperty("data")) { if(data.data[0]['seller_id'] != ''){ $('#statusupdate', window.parent.document).text( data.data[0]['seller_id']+ ':' + data.data[0]['seller_status'] +':'+ data.data[0]['buyer_id']+':'+ data.data[0]['buyer_status']).click(); } } window.parent.checkdata(data,user_id); if(data.hasownproperty("changed_user_id")) { $('#statusupdate', window.parent.document).text( data.changed_user_id+ ':' + data.changed_user_status +':'+ data.changed_user_id).click(); } }); </script> </body> </html> server . js
var app = require("express")(); var path = require('path'); var mysql = require("mysql"); var http = require('http').server(app); var io = require("socket.io")(http); var sockets = {}; var mysql = require('mysql'), connectionsarray = [], connection = mysql.createconnection({ multiplestatements: true, host: 'localhost', user: '*****', password: '******', database: 'transactionsdb', port: 3306 }), polling_interval = 1000, pollingtimer; // add redis comparing sql results againts cache var redis = require('redis'); var client = redis.createclient(); var express = require('express'); /* creating pool mysql connection.*/ var pool = mysql.createpool({ connectionlimit: 100, host: 'localhost', user: '*****', password: '*****', database: 'transactionsdb', debug: false }); var count = 0; var clients = []; function processalltransactions(sellsreply) { pool.query('select t.id,t.status,t.original_status, t.active, t.buyer_id, t.seller_id, t.seller_acked, t.seller_complete, t.buyer_complete, b.user_status buyer_status,t.chat_ended, s.user_status seller_status transaction t left join sf_guard_user_profile s on s.user_id = t.seller_id left join sf_guard_user_profile b on b.user_id = t.buyer_id active = 1 limit 1', [sellsreply], function (err, sells) { if (sells != '') { // attempt stop updates if it's not the active transaction client.get('active transaction id:'+sellsreply, function (err, active_transaction_id) { passed_active_transaction_id = active_transaction_id; }); // there trasnaction status defined , transation id not equal active transaction id if(sells[0].status !== undefined && sells[0].id !== passed_active_transaction_id ) { client.get('active transaction:'+sellsreply, function (err, data1) { if(json.stringify(sells) != data1){ client.set('active transaction id:'+sellsreply,sells[0]["id"]); client.set('active transaction:'+sellsreply,json.stringify(sells)); console.log(json.stringify(sells)); updatesockets({ data: sells // pass database result }); } }); } } }); } // method function getuserinfo(user_id, callback) { var query = connection.query('select user_status sf_guard_user_profile user_id = ' + connection.escape(user_id)); query.on('result', function (row) { callback(null, row.user_status); }); } var updatesockets = function (data) { // adding time of last update data.time = new date(); console.log('pushing new data clients connected ( connections amount = %s ) - %s', connectionsarray.length , data.time); // sending new data sockets connected connectionsarray.foreach(function (tmpsocket) { console.log(tmpsocket); tmpsocket.volatile.emit('notification', data); }); }; var pollingloop = function () { var socket; (var id in sockets) { socket = sockets[id]; client.get("uuid:" + socket.id, function (err, useridreply) { processalltransactions(useridreply); }); } connection.query('select * sf_guard_user_profile; select * transaction', function (err, result) { // error check if (err) { console.log(err); updatesockets(err); throw err; } else { // loop through queries var element = // compare cache results againt database query users result[0].foreach(function (element, index, array) { client.get('logged_in:' + element.user_id, function (err, reply) { if (reply === null) { // console.log( element.user_id + ' disconnected'); } else { // console.log(reply); } }); client.get("user:" + element.user_id, function (err, userreply) { if (element.user_status != userreply) { client.set('user:' + element.user_id, +element.user_status); changed_users.push(element); console.log(element.user_id + " set to: " + element.user_status); updatesockets({ changed_user_id: element.user_id, changed_user_status: element.user_status }); } }); }); } // loop on if there sockets still connected if (connectionsarray.length) { pollingtimer = settimeout(pollingloop, polling_interval); // reset changed users , changed transactions arrays changed_users = []; changed_transactions = []; } else { console.log('the server timer stopped because there no more socket connections on app'); } }); }; // count connections array array.prototype.contains = function (k, callback) { var self = this; return (function check(i) { if (i >= self.length) { return callback(false); } if (self[i] === k) { return callback(true); } return process.nexttick(check.bind(null, + 1)); }(0)); }; io.sockets.on('connection', function (socket) { // runs every connection sockets[socket.id] = socket; socket.on('client-data', function (data) { // user id url passed onload var user_id = data.url.replace('http://servernameremoved.com:4000/id/', ''); console.log('user id ' + user_id + ' connected session id ' + socket.id); client.set('uuid:' + socket.id, +user_id); }); console.log('number of connections:' + (connectionsarray.length)); // starting loop if @ least there 1 user connected if (!connectionsarray.length) { pollingloop(); } socket.on('disconnect', function (socketindex) { delete sockets[socket.id]; client.get("uuid:" + socket.id, function (err, userreply) { console.log('user id ' + userreply + ' got redis disconnected'); }); socketindex = connectionsarray.indexof(socket); console.log('socketid = %s got disconnected', socketindex); if (~socketindex) { connectionsarray.splice(socketindex, 1); } }); connectionsarray.push(socket); }); // express js route app.get('/id/:id', function (req, res) { clients.contains(req.params.id, function (found) { if (found) { console.log("found"); } else { client.set('logged_in:' + req.params.id, +req.params.id + 'is logged in'); } }); res.sendfile(__dirname + '/client.html'); }); // build server http.listen(4000, function () { console.log("server started"); }); here console log results
pushing new data clients connected ( connections amount = 2 ) - sat may 30 2015 21:16:23 gmt-0700 (pdt) 30 2015 21:15:15 gmt-0700 (pdt) user id 3 connected session id crttkril7ihq2yaeaaaa user id 2 connected session id wng7xdcedjhykbeiaaab *********************************************** [{"id":1,"status":20,"original_status":15,"active":1,"buyer_id":2,"seller_id":1,"seller_acked":1,"seller_complete":0,"buyer_complete":1,"buyer_status":4,"chat_ended":"2015-05-31t03:58:40.000z","seller_status":4}] *********************************************** pushing new data clients connected ( connections amount = 2 ) - sat may 30 2015 21:16:23 gmt-0700 (pdt) *********************************************** [{"id":1,"status":20,"original_status":15,"active":1,"buyer_id":2,"seller_id":1,"seller_acked":1,"seller_complete":0,"buyer_complete":1,"buyer_status":4,"chat_ended":"2015-05-31t03:58:40.000z","seller_status":4}] *********************************************** pushing new data clients connected ( connections amount = 2 ) - sat may 30 2015 21:16:23 gmt-0700 (pdt)
Comments
Post a Comment