I am working in Php with websockets for "one to one chat" module,I am new in "websockets", Here is my code
<script>
var conn = new WebSocket('ws://localhost:8282');
var client = {
user_id: <?php echo $user_id; ?>,
recipient_id: null,
type: 'socket',
token: null,
message: null
};
conn.onopen = function (e) {
conn.send(JSON.stringify(client));
$('#messages').append('<font color="green">Successfully connected as user ' + client.user_id + '</font><br>');
};
conn.onmessage = function (e) {
var data = JSON.parse(e.data);
if (data.message) {
$('#messages').append(data.user_id + ' : ' + data.message + '<br>');
}
if (data.type === 'token') {
$('#token').html('JWT Token : ' + data.token);
}
};
$('#submit').click(function () {
client.message = $('#text').val();
$('#messages').append(client.message + '<br>');
client.token = $('#token').text().split(': ')[1];
client.type = 'chat';
if ($('#recipient_id').val()) {
client.recipient_id = $('#recipient_id').val();
}
conn.send(JSON.stringify(client));
});
</script>
I want to know that
can we set "Userid" from our side ? or this "Userid" is issued by server ?
we are using "conn.onmessage" for receive message but which function should be use for receive "notifcation" (when specific notification come for specific user) ?
Related
Is it possible to make ajax post request in ServiceWorkers execution?
I have a Service Worker registered that just "listen" for a push notification.
I need to call a PHP function (in order to read some data from my database) during the execution of the Service Worker (when receiving the push notification), but I'm not able to do it. When I call the ajax post it goes to "error" section and the error is "No Transport" (I tried to add the "jQuery.support.cors = true;" like suggested in other thread, but this not fixed the issue).
Here below the serviceworker code.
Is it impossible to do what I'm trying to do, or I'm doing something wrong?
var document = self.document = {parentNode: null, nodeType: 9, toString: function() {return "FakeDocument"}};
var window = self.window = self;
var fakeElement = Object.create(document);
fakeElement.nodeType = 1;
fakeElement.toString=function() {return "FakeElement"};
fakeElement.parentNode = fakeElement.firstChild = fakeElement.lastChild = fakeElement;
fakeElement.ownerDocument = document;
document.head = document.body = fakeElement;
document.ownerDocument = document.documentElement = document;
document.getElementById = document.createElement = function() {return fakeElement;};
document.createDocumentFragment = function() {return this;};
document.getElementsByTagName = document.getElementsByClassName = function() {return [fakeElement];};
document.getAttribute = document.setAttribute = document.removeChild =
document.addEventListener = document.removeEventListener =
function() {return null;};
document.cloneNode = document.appendChild = function() {return this;};
document.appendChild = function(child) {return child;};
importScripts('js/jquery.js');
self.addEventListener('push', function(event) {
jQuery.support.cors = true;
var endpoint = "";
if (event.data) {
endpoint = event.data.text();
}
var data = {
query: "SELECT * FROM [TABLE] WHERE ENDPOINT = '" + endpoint + "'"
};
$.ajax({
data: data,
method: "POST",
url: 'ExecuteQueryJquery.php',
dataType: 'json',
success: function (obj, textstatus) {
var o = obj;
},
error: function (obj, textstatus) {
var o = obj;
}
});
});
Good day,
I am trying to create a script that loads my Browser Geolocation and following sends it to a file that saves it.
The problem is. The data does not get send.
And an even bigger problem is that I have tried many things but I am quite clueless.
I added several alerts but the alerts do not show up.
What should the script do?
Run once every five seconds and requesting your GeoLocation.
When you click accept on your phone and accept for all from this source you will have an active GPS alike tracking.
The code :
<script type="text/javascript">
function success(position) {
///SaveActiveGeoLocation();
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}
else{
error('not supported');
}
function SaveGeoLocation(){
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// **** SEND TYPE
url : "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data : {
'Lat' : Lat,
'Lon' : Lon,
'GeoAccuracy' : Accuracy
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response == "ok" ){
alert('SEND!');
}
else{
alert( "Response = " + response );
}
}
}
);
}
$(document).ready(function() {
$.ajaxSetup({
cache: false
}); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
///alert('HOI!');
SaveGeoLocation();
}, 5000);
// the "10000" here refers to the time to refresh the div. it is in milliseconds.
/// **** DEFAULT LOADING
///SaveGeoLocation();
});
</script>
The file that saves the send POST data :
<?php
include('function.geolocation.class.php');
$geo = new GeoLocation();
$Lat = $_POST['Lat'];
$Lon = $_POST['Lon'];
$GeoAccuracy = $_POST['GeoAccuracy'];
$IP = $geo->GetIP();
$file = 'location.txt';
$address = $geo->getAddress($Lat, $Lon);
$contents = $Lat.'|'.$Lon.'|'.$IP.'|'.$GeoAccuracy.'|'.date('Y-m-d H:i:s').'|'.$address.PHP_EOL;
$handle = fopen($file, 'a');
fwrite($handle, $contents);
fclose($handle);
echo 'ok';
?>
One problem I can see is the variable position does not exists in the context of the SaveGeoLocation method
function success(position) {
//SaveActiveGeoLocation();
window.position = position;
}
function SaveGeoLocation() {
if (!window.position) {
return;
}
//your stuff
}
There is no need to call SaveGeoLocation using interval, you can call SaveGeoLocation from the success callback like
function success(position) {
SaveActiveGeoLocation(position);
}
function SaveGeoLocation(position) {
//your stuff
}
If you want to save the location continuously
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
function saveLocation() {
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
var Lat = position.coords.latitude;
var Lon = position.coords.longitude;
var Accuracy = position.coords.accuracy;
///######## SENDING THE INFORMATION BY AJAX
$.ajax({
type: "POST", /// **** SEND TYPE
url: "savegeo.php", /// **** TARGET FILE TO FETCH THE DATA
data: {
'Lat': Lat,
'Lon': Lon,
'GeoAccuracy': Accuracy
},
///######## IN CASE OF SUCCESS
success: function (response) {}
}).done(function (response) {
if (response == "ok") {
alert('SEND!');
} else {
alert("Response = " + response);
}
}).always(function () {
setTimeout(saveLocation, 5000)
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
}
if (navigator.geolocation) {
saveLocation();
} else {
error('not supported');
}
});
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);
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.
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);
});