How to make client talk to server in same node proccess? - php

I have an application written in SSJS (Node) ... This application needs to serve data to the php script that will request by fsockopen .. All right here ... This server needs to collect data from a second server through a persistent connection. How to do this? Making the same process coordinate these connections? Is this possible?
var net = require('net');
/* #############################################
# "CLIENT" Used to connect to data server
# ---------------------------------
#############################################
*/
var clientConnect = net.createConnection(port, host);
clientConnect.setEncoding('utf8');
clientConnect.on('connect', function () {
console.log('Client','Connected to CAGEAPI');
clientConnect.write('user#pass');
});
clientConnectt.on('data', function (data) {
console.log('Client','Data received: ' + data);
});
clientConnect.on('close', function(code) {
console.log('Client','Connection closed');
});
clientConnect.on('error', function (err) {
console.log(err);
});
/* ################################################
#
# "SERVER" Used to serv data to PHPScripts
# --------------------------------
################################################
*/
var handleServer = net.createServer(function(server) {
console.log('Server','CONNECTED: ' + server.remoteAddress +':'+ server.remotePort);
server.on('data', function(data) {
console.log('Server','DATA ' + server.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
server.write('You said "' + data + '"');
});
// Add a 'close' event handler to this instance of socket
server.on('close', function(data) {
console.log('Server','CLOSED: ' + server.remoteAddress +' '+ server.remotePort);
});
}).listen(port2, host2);
Both (Client and server) is working fine... But how to make they talk each other?

I think you're probably after something like this:
/*jslint node: true, white: true */
// Declare constructors
var DataSource, PHPClientServer;
// The DataSource class
// Handles connecting/reconnecting to the data source, and piping endpoints together
(function() {
"use strict";
DataSource = function(net)
{
this.net = net;
};
DataSource.prototype.net = null;
DataSource.prototype.host = 'localhost';
DataSource.prototype.port = 0;
DataSource.prototype.user = '';
DataSource.prototype.pass = '';
DataSource.prototype.socket = null;
DataSource.prototype.currentClient = null;
DataSource.prototype.start = function(host, port, user, pass)
{
if (host !== undefined) {
this.host = host;
}
if (port !== undefined) {
this.port = port;
}
if (user !== undefined) {
this.user = user;
}
if (pass !== undefined) {
this.pass = pass;
}
this.socket = this.net.createConnection(this.port, this.host);
this.socket.on('connect', function () {
console.log('Data source connected');
this.socket.write(this.user + '#' + this.pass);
}.bind(this));
this.socket.on('error', function() {
console.error('Error on data source connection');
this.stop();
this.start();
}.bind(this));
this.socket.on('end', function() {
console.error('Data source connection terminated');
this.stop();
this.start();
}.bind(this));
};
DataSource.prototype.stop = function()
{
this.socket.end();
this.socket = null;
};
DataSource.prototype.attachClient = function(client)
{
console.log('Attaching client to data source');
this.currentClient = client;
this.socket.pipe(this.currentClient);
this.currentClient.pipe(this.socket, {end: false});
};
DataSource.prototype.detachCurrentClient = function()
{
console.log('Detaching client from data source');
this.socket.unpipe(this.currentClient);
this.currentClient.unpipe(this.socket);
this.currentClient = null;
};
DataSource.prototype.hasClient = function()
{
return this.currentClient !== null;
};
}());
// The PHPClientServer class
// Handles the server operations for PHP clients
(function() {
"use strict";
PHPClientServer = function(net, dataSource)
{
this.net = net;
this.dataSource = dataSource;
this.pendingClientStack = [];
};
PHPClientServer.prototype.net = null;
PHPClientServer.prototype.dataSource = null;
PHPClientServer.prototype.host = null;
PHPClientServer.prototype.port = null;
PHPClientServer.prototype.server = null;
PHPClientServer.prototype.pendingClientStack = null;
PHPClientServer.prototype.start = function(host, port)
{
var clientTerminateHandler = function() {
console.log('Client disconnected');
this.dataSource.detachCurrentClient();
if (this.pendingClientStack.length) {
console.log('Attaching next client in queue');
this.dataSource.attachClient(this.pendingClientStack.shift());
}
}.bind(this);
if (host !== undefined) {
this.host = host;
}
if (port !== undefined) {
this.port = port;
}
this.server = this.net.createServer(function(client) {
console.log('Client connected');
client.on('end', clientTerminateHandler);
client.on('error', clientTerminateHandler);
if (this.dataSource.hasClient()) {
console.log('Client added to queue');
this.pendingClientStack.push(client);
} else {
this.dataSource.attachClient(client);
}
}.bind(this));
this.server.listen(this.port, this.host);
};
PHPClientServer.prototype.stop = function()
{
this.server.close();
this.server = null;
};
}());
// Bootstrap
var net, dataSource, server;
net = require('net');
dataSource = new DataSource(net);
dataSource.start('192.168.0.1', 23);
server = new PHPClientServer(net, dataSource);
server.start('0.0.0.0', 12345);
I realise that's a wall of code with minimal explanation, so please ask if there's something you don't understand.
Also, before anyone says it, yes I am fully aware that I am treating a prototypical OOP language as if it were a classical one, Javascript != Java, yada yada yada. I don't care, I like to work with Javascript in this manner.

Related

avoiding duplicate mysql injection

I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}
Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};

How to Sync PHP and NodeJS with Redis and get data in order

I have a example code for make experiments trying to think "how to ""sync"" nodejs and php in a simple chat example.
Here is my NodeJS server:
var redis = require('redis'),
subscriber = redis.createClient(),
publisher = redis.createClient();
//var sckio = require('socket.io').listen(8888);
var http = require('http');
var querystring = require('querystring');
var WebSocketServer = require('ws').Server
var ENCODING = 'utf8';
var tCounter = 0;
/* #################################### */
// Event on "subscribe" to any channel
subscriber.on("subscribe", function (channel, count) {
// Publish to redis server Test Message
publisher.publish("chat", "NODEJS MESSAGE");
});
// Suscrib to redis server
subscriber.on('message', function (channel, json) {
console.log('SUB: ' + channel + ' | ' + json);
console.log('PHP PUSH TO REDIS, AND NODE CAPTURE REDIS PUSH: ' + (getMicrotime(true) - tCounter));
});
subscriber.subscribe('chat'); // Subs to "mysql" channel
/*
var clients = [];
sckio.sockets.on('connection', function (socket) {
clients.push(socket);
publisher.publish("chat", "User connected");
socket.on('message', function (from, msg) {
publisher.publish("chat", msg);
clients.forEach(function (client) {
if (client === socket) return;
client.send(msg);
});
});
socket.on('disconnect', function () {
clients.splice(clients.indexOf(socket), 1);
publisher.publish("chat", "User disconnected");
});
});
*/
var wss = new WebSocketServer({port: 8888, timeout : 500});
var wsClients = [];
wss.on('connection', function(ws) {
ws.AUTH_ID = Math.random();
wsClients.push(ws);
publisher.publish("chat", "User enter");
ws.on('message', function(message) {
wsClients.forEach(function (client) {
client.send(ws.AUTH_ID + ' ' + message);
});
tCounter = getMicrotime(true);
console.log('CALL TO PHP: ' + tCounter);
PostCode('CODE TO PHP FROM NODE', function() {
wsClients.forEach(function (client) {
client.send('PHP SAVE DATA');
});
});
});
ws.on('close', function(message) {
wsClients.splice(wsClients.indexOf(ws), 1);
publisher.publish("chat", "User left");
});
ws.send('HELLO USER!');
});
function getMicrotime(get_as_float) {
var now = new Date().getTime() / 1000;
var s = parseInt(now, 10);
return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}
function PostCode(codestring, callback) {
// Build the post string from an object
var post_data = querystring.stringify({
'output_format': 'json',
'js_code' : codestring
});
// An object of options to indicate where to post to
var post_options = {
host: '127.0.0.1',
port: '80',
path: '/NodeJS/chat_system/php_system.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
// Set up the request
var post_req = http.request(post_options, function(res) {
res.setEncoding(ENCODING);
res.on('data', function (chunk) {
console.log('Response FROM PHP: ' + chunk);
if (typeof callback == 'function') {
callback(chunk);
}
});
});
// post the data
post_req.write(post_data);
post_req.end();
}
Here is my PHP Server
require 'Predis/Autoloader.php';
Predis\Autoloader::register();
function pushToRedis($data) {
try {
$redis = new Predis\Client(array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
));
} catch (Exception $e) {
echo "Couldn't connected to Redis";
echo $e->getMessage();
return false;
}
$json = json_encode($data);
$redis->publish("chat", $json);
return true;
}
pushToRedis('PHP PUSH TO REDIS!');
header('Content-Type: application/json');
echo json_encode(array('response' => print_r(array($_REQUEST, $_SERVER), true)));
And my client:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebSockets - Simple chat</title>
<style>
.chat { width: 400px; height: 250px; overflow-y: scroll; }
</style>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
var connection = new WebSocket('ws://127.0.0.1:8888');
$(document).ready(function() {
/*
var socket = io.connect('http://127.0.0.1:8888');
socket.on('message', function (data) {
alert(data);
});
socket.send('HELLO!');
*/
connection.onopen = function () {
console.log('connected!');
};
connection.onerror = function (error) {
};
connection.onmessage = function (message) {
$('.chat').append(message.data + '<br>');
$('.chat').scrollTop($('.chat')[0].scrollHeight);
};
$('input[name="text"]').on('keydown', function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
connection.send(msg);
$(this).val('').focus();
}
});
});
</script>
<div class="chat">
</div>
<input type="text" name="text">
</body>
</html>
The problem is the order of the PHP return the response to NodeJS via Redis when the network its bussy.
For example: I send more messages from de javascript client, then, NodeJS call to PHP every message, PHP save the data in MYSQL, and call Redis, NodeJS detect the Redis push and update the clients. But, in some cases, if i send from the Javascript client in loop some messages ( for(0-10000)) I dont reply to others clients in the same order, in cases geting numbers like 200,201,300,202,320,203 in the clients.
I think this is for the PHP delay to response.
My question is How i can manage the responses to update the clients, in the correct order? because this problem can cause, to clients receive the chat messages in wrong order.
But why you want to use php you able to send data to mysql directly using mysql package of nodejs
You may install mysql package via :
npm install mysql
Connection made by :
mysql = require('mysql'),
connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database name',
port: 3306
}),
And throw query by using :
var q=connection.query('select * from table);

Node.js server sends back EOF block the PHP server

I have a node.js server opening 8000 port. It is a chat server.
I have another PHP server and I use proxy + virtual host so when I go www.phpserver.com/chat It proxies to the node.js server. I did this so I can use ajax to call the node.js server.
Right now, everything works fine when i run the node.js server, however, after a while (a random time frame, not necessarily long or short), the PHP server will crush because it gets an EOF from the node.js server and it's just stuck there until I stop/restart the node.js server.
The error I get is(from php error log):
(70014)End of file found: proxy: error reading status line from remote
server nodeserver.com:8000, referer: https://www.phpserver.com
I asked some professionals and they said it's because of the PHP server sends the request to the node.js server successfully and receives an EOF or fails to receive any response. I don't understand how to fix it tho. What should I do so even the node.js server crushes, it won't crush the PHP server? Should I get rid of the proxy+ajax and starts to use socket.io?
Please advise.
Thank you!
Below is some node codes.
From middleware:
this.events.addListener('update', o_.bind(function(package) {
if(this.clear != 0){
delete this.sessions[this.clear];
}
var _package = package.toJSON();
if(package.type == 'status' && package.status == 'offline') {
var sids = Object.keys(this.sessions), sid, sess;
for(sid in this.sessions) {
sess = this.sessions[sid];
if(sess.data('username') == package.username) {
if(sess.listeners.length)
sess.send(200, {type: 'goodbye'});
delete this.sessions[sid];
break;
}
}
}
}, this));
};
Hub.prototype.destroy = function(sid, fn) {
this.set(sid, null, fn);
};
Hub.prototype.reap = function(ms) {
var threshold = +new Date - ms,
sids = Object.keys(this.sessions);
for(var i = 0, len = sids.length; i < len; ++i) {
var sid = sids[i], sess = this.sessions[sid];
if(sess.lastAccess < threshold) {
this.events.emit('update', new packages.Offline(sess.data('username')));
}
}
};
Hub.prototype.get = function(req, fn) {
if(this.sessions[req.sessionID]) {
fn(null, this.sessions[req.sessionID]);
} else {
this.auth.authenticate(req, o_.bind(function(data) {
if(data) {
var session = new User(req.sessionID, data);
this.set(req.sessionID, session);
this.auth.friends(req, data, o_.bind(function(friends) {
var friends_copy = friends.slice();
o_.values(this.sessions).filter(function(friend) {
return ~friends.indexOf(friend.data('username'));
}).forEach(function(friend) {
var username = friend.data('username');
friends_copy[friends_copy.indexOf(username)] =
[username, friend.status()];
}, this);
session._friends(friends_copy);
console.log("refreshed");
session.events.addListener('status',
o_.bind(function(value, message) {
this.events.emit(
'update',
new packages.Status(session.data('username'),
value,
message)
);
}, this));
this.events.addListener('update',
o_.bind(session.receivedUpdate, session));
this.set(req.sessionID, session);
fn(null, session);
}, this));
} else {
fn();
}
}, this));
}
};
From app.js
#!/usr/bin/env node
var sys = require('sys'),
express = require('express'),
packages = require('./libs/packages'),
fs = require('fs'),
o_ = require('./libs/utils'),
https = require('https');
o_.merge(global, require('./settings'));
try { o_.merge(global, require('./settings.local')); } catch(e) {}
try {
var daemon = require('./libs/daemon/daemon'),
start = function() {
daemon.init({
lock: PID_FILE,
stdin: '/dev/null',
stdout: LOG_FILE,
stderr: LOG_FILE,
umask: 0,
chroot: null,
chdir: '.'
});
},
stop = function() {
process.kill(parseInt(require('fs').readFileSync(PID_FILE)));
};
switch(process.argv[2]) {
case 'stop':
stop();
process.exit(0);
break;
case 'start':
if(process.argv[3])
process.env.EXPRESS_ENV = process.argv[3];
start();
break;
case 'restart':
stop();
start();
process.exit(0);
break;
case 'help':
sys.puts('Usage: node app.js [start|stop|restart]');
process.exit(0);
break;
}
} catch(e) {
sys.puts('Daemon library not found! Please compile ' +
'./libs/daemon/daemon.node if you would like to use it.');
}
var options = {
key: fs.readFileSync('/home/ec2-user/key.pem'),
cert: fs.readFileSync('/home/ec2-user/cert.pem'),
ca: fs.readFileSync('/home/ec2-user/ca.pem'),
};
var app = express();
//app.set('env', 'development');
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(require('./middleware/im')({
maxAge: 30 * 1000,
reapInterval: 20 * 1000,
authentication: require('./libs/authentication/' + AUTH_LIBRARY)
}));
app.set('root', __dirname);
if ('development' == app.get('env')) {
app.set('view engine', 'jade');
app.set('views', __dirname + '/dev/views');
app.stack.unshift({
route: '/dev',
handle: function(req, res, next) {
req.dev = true;
next();
}
});
app.use(express.logger());
require('./dev/app')('/dev', app);
app.use(express.static(
require('path').join(__dirname, '../client')));
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
}
//app.listen(APP_PORT, APP_HOST);
// Listener endpoint; handled in middleware
app.get('/listen', function(){});
app.post('/message', function(req, res) {
res.find(req.body['to'], function(user) {
if(!user)
return res.send(new packages.Error('not online'));
res.message(user, new packages.Message(
req.session.data('username'),
req.body.body
));
});
});
app.post('/message/typing', function(req, res) {
if(~packages.TYPING_STATES.indexOf('typing' + req.body['state'])) {
res.find(req.body['to'], function(user) {
if(user) {
res.message(user, new packages.Status(
req.session.data('username'),
'typing' + req.body.state
));
}
// Typing updates do not receive confirmations,
// as they are not important enough.
res.send('');
});
} else {
res.send(new packages.Error('invalid state'));
}
});
app.post('/status', function(req, res) {
if(~packages.STATUSES.indexOf(req.body['status'])) {
res.status(req.body.status, req.body.message);
res.send(new packages.Success('status updated'));
} else {
res.send(new packages.Error('invalid status'));
}
});
app.post('/online', function(req, res) {
var d = new Date();
var n = d.getTime() + 30;
req.sessionID.expires = n;
res.status(req.body.status, 'available');
});
app.post('/signoff', function(req, res) {
res.signOff();
res.send(new packages.Success('goodbye'));
});
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Error on the node/express server.');
});
https.createServer(options, app).listen(8000);
I can't help you answer your question but I can try to point you in a right direction.
I'm currently working on a Node JS server myself, and I found very useful to have a logger setup.
There are a few of them, but my favorite is Winston so far.
Reference: https://github.com/flatiron/winston
To install Winston for your Node JS server (seems you have already installed a few modules):
npm install winston
Then I have logger module setup as (logger.js):
/**
* Usage:
* - logger.info('sample text');
* - logger.warn('sample text');
* - logger.error('sample text');
*/
// Load modules
var winston = require('winston');
// Create custom logger
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/debug.log', json: false })
],
exceptionHandlers: [
new (winston.transports.Console)({ json: false, timestamp: true }),
new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
],
exitOnError: false
});
// Export logger
module.exports = logger;
Finally I load in Winston logger module into my server scripts by:
var logger = require('./logger');
It will automatically log any exceptions into exceptions.log on your Node JS server location. It helped me out a lot to catch exceptions I haven't noticed before within Node JS unrelated to PHP.
P.S. Also check out socket.io, that may simplify what you are trying to do.

weird node.js and redis behaviour

I've got a problem that defies explanation. Here's what i want:
Client connects to node server through socket.io, sends his SID
Redis verifies if said SID is in its store, if not, don't emit 'authenticated', if the sid is in the store, then emit 'authenticated'
Upon receiving the authentication, the extra options are given
Sounds pretty straightforward, and it should be. However this happens:
Client connects with a SID thats in the redis store
Node.js server verifies that the SID is in the store but fails to emit said 'authenticated'
However, when i restart the node server, everything seems to work just fine :S. But when i proceed to remove the key from the store, and add it again (by ?auth and ?logout) the 'authenticated' is again not emitted.
Client code:
<?php
session_start();
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
require "./libraries/Predis.php";
if(isset($_GET['logout'])) {
session_regenerate_id();
}
$sid = sha1(session_id());
$redis = new Predis\Client();
echo "<h1>SID: " . $sid . "</h1>";
if(isset($_GET['auth'])) {
$redis->set($sid, mt_rand(1,20000));
$redis->expire($sid, 1800);
echo "auth set<br />";
}
if ($redis->get($sid)) {
// he is authenticad, show something else
echo "auth found<br />";
}
?>
<html>
<head>
<title>Node Test VTclient</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://the_server.dev:11337/socket.io/socket.io.js"></script>
</head>
<body>
<p id="text">access denied</p>
<script type="text/javascript">
var connected = false;
var authenticated = false;
if(typeof io == 'undefined') {
trigger_error();
} else {
var socket = io.connect('http://vtvserver.dev:11337/', {
'reconnection delay' : 1,
'max reconnection attempts' : 1
});
socket.on('connect', function (data) {
connected = true;
socket.emit('success_connect',{sid: '<?php echo $sid; ?>'});
$('#text').html('connected');
socket.on('get_bids', function (data) {
$('#bids').html('');
if(typeof data === 'object') {
$.each(data.rows, function(key, value) {
add_bid(value.bid_id, value.bid_amount);
});
}
}).on('reconnecting', function (reason) {
trigger_error(reason);
$('#text').html('disconnected');
socket.disconnect();
}).on('authenticated', function(data) {
$('#text').html('authorised!');
// successful auth
$('#bidding').show();
}).on('disconnect', function (data) {
connected = false;
}).on('bid_placed', function (data) {
add_bid(data.id, data.amount);
}).on('own_bid_placed', function(data){
if(!data.error) {
alert('bieding geplaatst!');
} else {
alert('Uw bieding is ongeldig.');
}
});
});
}
function trigger_error(reason) {
$('#text').html('Server is down...');
}
function add_bid(id, amount) {
$('#bids').append($('<option>', { value : id }).text(amount));
}
$(function() {
$('#disconnect').click(function() {
if(connected === true) {
socket.disconnect();
$('#text').html('Disconnected from server.');
}
});
$('#bid').click(function() {
var amount = $('#amount').val();
// commit the bid to the server
socket.emit('add_bid', {amount: amount});
});
})
</script>
<label for="bids">Biedingen:</label>
<select name="bids" id="bids" multiple='multiple' style='width:100px; height:150px'></select>
<fieldset style="display:none" id="bidding">
<legend>Plaats bieding</legend>
<label for="amount"><Bedrag: </label><input type="text" id="amount" name="amount" value='0' />
<button id="bid">Bied</button>
</fieldset>
<button id="disconnect">Disconnect</button>
</body>
Server code:
var
cfg = require("./config").cfg(),
sys = require("sys"),
url = require("url"),
http = require("http"),
qs = require("querystring"),
redis = require("redis"),
redis_client = redis.createClient(cfg.redis.port, cfg.redis.host),
express = require("express"),
mysql = require("./node_modules/mysql"),
//ch = require("./node_modules/channel").channel(cfg.msg_backlog, cfg.msg_truncate),
sio = require('./node_modules/socket.io');
//require ('./node_modules/sherpa');
//require ('./node_modules/log');
require ('./node_modules/simplejsonp');
redis_client.on("error", function (err) {
console.log("REDIS error: " + err);
});
var app = express();
app.configure(function(){
});
app.get('/',
function (req,res) {
if (req.headers['referer']) {
log(req.connection.remoteAddress + " / " + req.headers['referer']);
}
else {
log(req.connection.remoteAddress + " /");
}
res.writeHead(307, {'Location':'http://' + cfg.domain});
res.end();
});
app.listen(cfg.server_port, cfg.server_public_ip);
/* Create the IO server */
var server = http.createServer(app);
var io = sio.listen(server);
// minify the browser socket io client
io.enable('browser client minification');
server.listen(11337);
io.set('log level', 2);
io.sockets.on('disconnect', function(data) {
console.log('client disconnected');
});
/**
* Enable authentication
* #param {[type]} handshakeData [description]
* #param {Function} callback [description]
* #return {[type]} [description]
*/
// Anonymous or authenticaed user?
io.on('connection', function (socket) {
var sql_client = mysql.createClient({
host : cfg.database.server,
user : cfg.database.user,
password : cfg.database.pass,
database : cfg.database.primary
});
console.log('incoming connection');
socket.emit('access', 'granted');
socket.on('success_connect', function(data) {
console.log('Client connected: ' + data.sid);
sql_client.query('SELECT * FROM `bids`',function(error, results) {
if(error) {
console.log('Error: ' + error);
return false;
}
console.log('emitting get_bids...');
socket.emit('get_bids', {rows: results});
});
// if the user is authenticated, flag it as such
redis_client.get(data.sid, function(err, reply) {
var authenticated = false;
if(err) {
console.log("Fatal error: " + err);
}
console.log('Got response from redis...');
if(reply !== null) {
console.log('auth succesful for '+data.sid);
socket.emit('authenticated', { sid : data.sid});
authenticated = true;
}
// LEFT JOIN user_bids ON user_bids_bid_id = bid_id
if(authenticated === true) {
// safest way: only listen for certain commands when the user is autenticated
socket.on('add_bid', function(data) {
var amount = data.amount;
var values = [amount];
var error = false;
// validate the amount
var regexp = new RegExp(/^\d{1,5}(\.\d{1,2})?$/);
if(typeof amount === 'undefined' || amount < 1.00 || !amount.match(regexp)) {
error = 'invalid_bid';
}
socket.emit('own_bid_placed', {amount: amount, error : error});
if(!error) {
sql_client.query('INSERT INTO `bids` SET bid_amount = ?',values,function(error, results) {
if(error) {
console.log('Error: ' + error);
}
console.log('Inserted: ' + results.affectedRows + ' row.');
console.log('Id inserted: ' + results.insertId);
io.sockets.emit('bid_placed', {id: results.insertId, amount: amount});
});
}
});
}
});
});
sql_client.end();
socket.on('disconnect', function(data) {
console.log('Client disconnected');
});
});
console.log('Server running at http://'+cfg.server_public_ip+':'+cfg.server_port+'/');
I fixed it by creating the redis client when a client connects:
io.on('connection', function (socket) {
var redis_client = redis.createClient(cfg.redis.port, cfg.redis.host);
});

NGiNX Http Push Module - broadcast behaves random

The symptoms: I have the "push_listener_concurrency" set to "broadcast" but only several (random amount) of subscribers get the message. Was anybody dealing with this type of problem? The test cases are pretty straight-forward I 'POST' to a '/publisher?cid=test' channel and 'GET' from a '/listener?cid=test' everything seems to be working when there's only one client per channel...
Just in case somebody will face the same problem.
There were a problem with headers. To listen the nginx http push module correctly with jQuery you should use a listener that processes the headers correctly here is my code:
function Listener(url, successCallback, failureCallback) {
var scope = this;
var etag = 0, lastModified = 0;
var launched = false;
var failure = false;
this.successTimeout = 0;
this.failureTimeout = 5000;
var getTimeout = function () {
return failure ? this.failureTimeout : this.successTimeout;
};
var listen = function () {
$.ajax(scope.ajaxOptions);
}
var beforeSend = function (jqXHR) {
jqXHR.setRequestHeader("If-None-Match", etag);
jqXHR.setRequestHeader("If-Modified-Since", lastModified);
};
var complete = function (jqXHR) {
var timeout = getTimeout();
etag = jqXHR.getResponseHeader('Etag');
lastModified = jqXHR.getResponseHeader('Last-Modified');
var timeout = jqXHR.statusText == 'success' ? scope.successTimeout : scope.failureTimeout;
if (timeout > 0) {
setTimeout(listen, timeout);
} else {
listen();
}
};
this.ajaxOptions = {
url : url,
type : 'GET',
async : true,
error : failureCallback,
success : successCallback,
dataType : 'json',
complete : complete,
beforeSend : beforeSend,
timeout: 1000 * 60 * 60 * 24
};
this.start = function (timeout) {
if (!launched) {
if (typeof(timeout) == 'undefined' || timeout == 0) {
listen();
} else {
setTimeout(listen, timeout);
}
launched = true;
}
};
}

Categories