Socket.io 'Cannot connect'. Client on different domain/port - node.js

I'm having trouble connecting to socket.io with the client being located on a different port, on the same machine.
The client is part of a site run on Apache (port 80) and Nodejs is being run on 8585.
Any idea what I'm doing wrong here?
On the client side, I get the 'Unable to connect Socket.IO' message, with no reason.
Server:
var express = require('express'),
connect = require('connect'),
RedisStore = require('connect-redis')(express),
io = require('socket.io').listen(app),
routes = require('./routes'),
request = require('request');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: "secret", store: new RedisStore}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
io.set('authorization', function(handshakeData, callback) {
console.log('authorization');
callback(null, true);
});
//Socket IO connection
io.sockets.on('connection', function (socket) {
var session = socket.handshake.session;
console.log(session);
});
app.listen(8585);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Client: (run from a site on apache and different domain, but same server).
var sio = io.connect('http://localhost:8585');
sio.socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
sio.on('connect', function (){
console.error('successfully established a working connection \o/');
});
Thank you!

Unless you're running the browser on the same computer as the server, "localhost" in your code will refer to the computer running the browser, not the server. DNS lookups for localhost always resolve to the computer doing the lookup. And even if you're accessing the site on the same computer as the server, unless you're accessing it as "localhost", the browser's security policies will prevent you from talking to localhost.

Related

Multiple ports node.js application deployment on web/cloud

I have an electronic board, which collects data from sensors and I hope to send it to an web service, which then does some processing and sends the results to an website, when URL is entered. I use multiple ports for this. One port listens for UDP connection and other port is for HTTP. The code works fine on my local machine. Here is the code
var net = require('net')
,dgram = require('dgram')
,express = require('express')
,io = require('socket.io')
,routes = require('./routes')
,http = require('http')
,fs = require('fs');
var app = module.exports = express.createServer();
var HOST = '192.168.0.132'
var PORT = 1337
var datarr = []
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout:false, pretty:true});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
//ROUTES
app.get('/',routes.index);
//UDP Server
var decoder = new (require('string_decoder').StringDecoder)('utf-8')
var buffer = '';
var server = dgram.createSocket('udp4');
server.on('listening',function() {
console.log('Listening');
});
server.on('message', function(data,rinfo) {
console.log(decoder.write(data));
io.sockets.emit('data',decoder.write(data));
});
server.on('close', function(data) {
console.log('closed');
});
server.bind(1337,'192.168.0.132');
//UDP server ends
var io=require('socket.io').listen(app);
app.listen(1185);
io.sockets.on('connection',function (socket) {
console.log('Hello Got a connection');
});
console.log("server listening");
I know it can't be hosted on heroku, because it allows only one port.
What are my options?
1)According to some answers on this website, websockets. But i have no idea on how to set up websocket between udp and http server. Any links to websites/github would be very helful.
2)Hosting services which allow multiple ports. Are there any which provide this service? Links to documentations will be appreciated.
Thanks in advance.
You can do some thing like this
var port = process.env.PORT || 1185;
and then use this port variable as
app.listen(port);
every time when you need to run on different port just use
PORT = node app.js

Using Redis as a session store in Node js and how to get values from it?

I used Redis to store session in my nodejs server. This is my code:
var express = require('express');
var http = require('http');
var connect = require("connect");
var path = require('path');
var RedisStore = require("connect-redis")(express);
var redis = require("redis").createClient();
var app = express();
app.set('port', 8888);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.session({secret: 'blues',
cookie: { secure: true },
store: new RedisStore({
host: 'localhost',
port: 6379,
client: redis })
}));
app.use(express.static(path.join(__dirname, 'public')));
app.engine('html', require('ejs').renderFile);
app.get('/login', function(req,res){
res.render('login.html', {title: 'Login'});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
When I run the server, and access the url http://localhost:8888/login, then come back to check the Redis server, I found 3 sessions saved there, like this
127.0.0.1:6379> keys *
1) "sess:DGtMAO3pRPExzPjFS_B07bXP"
2) "sess:bzPTRrlXXe1DhzNze0JdZswt"
3) "sess:-RM8kkNtJ0jj3nhuYmiuw0f6"
What does it mean? Why 3 sessions (I had double-check with FLUSHDB command)?
EDIT: Ok I have some test and it turns out the other two sessions is from a css and a js file in login.html. But there are something I don't understand that when I press F5, 3 new session is stored in Redis. Why is that? Didn't session stay the same until it expire?
Another problem is, with above code how can I retrieve the session saved in Redis? I used this:
redis.get('"sess:' + req.session.id + '"', function(err, result){
console.log("Get session: " + util.inspect(result,{ showHidden: true, depth: null }));
});
it return null, although I can retrieve it with the same req.session.id in Redis server.
Please help me. Thank you!

Node.js buffering socket data

I am using current versions of all things node.js, express.js, socket.io etc ... I am trying to connect to a server who's sole purpose in life is just spew text and in turn send it to web client connected via socket.io. The text is nothing more character strings with standard line endings and the max data rate is something on the order of 1024bytes/sec. My code, the core bits, is something like this
var express = require('express')
, app = express()
, routes = require('./routes')
, user = require('./routes/user')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, path = require('path')
, dataSourcePort = 5000
, host = "10.0.1.32"
, dataStream = require('net').createConnection(dataSourcePort, host);
dataStream.setEncoding('utf8');
io.sockets.on('connection', function (socket) {
dataStream.on('data',function(data){
socket.emit("stuff",data);
});
});
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
This works all fine and dandy but, every once in a while it just hangs, as in the data stops going out to the clients. I assume a buffer gets stuffed somewhere along the line but, not sure. Is there a better way to do this and avoid the stuffing part?
The main issue I see is that you never unbind your data handler, so as people connect and disconnect, you will accumulate data listeners and memory usage, and waste resources trying to send data to disconnected sockets.
io.sockets.on('connection', function (socket) {
function ondata(data){
socket.emit("stuff",data);
}
function ondisconnect(){
dataStream.off('data', ondata);
socket.off('disconnect', ondisconnect);
}
dataStream.on('data', ondata);
socket.on('disconnect', ondisconnect);
});

Nodejs simple socket.io example not working

I've the following Server Side Code:
var express = require('express')
, http = require('http')
, routes = require('./routes')
, io = require('socket.io')
, factory = require('./serverfactory.js');
var app = express();
var server = app.listen(3000);
io = io.listen(server);
io.sockets.on('connection',function(socket){
console.log('new user');
socket.emit('hail','mysimplemsg');
socket.on('customevent',function(msg){
console.log(msg);
});
});
//var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
And this is the client side :
var socket = io.connect('http://localhost:3000');
socket.emit('customevent','work');
socket.on('hail',function(msg){
console.log(msg);
});
I am expecting that my git console outputs new user (which it does) then it should output work (which it does not) then i get a msg in my browser console mysimplemsg (which it does not).
Whats going on why the event at server side that is customevent is not called and why the event at the client side that is hail is not called ?
I believe the issue is that you are emitting customevent from the client before you are connected. Try adding a connect handler and moving your client side emit into it:
var socket = io.connect('http://localhost:3000');
socket.on('hail',function(msg){
console.log(msg);
});
socket.on('connect',function(){
console.log('connected to socket.io server');
socket.emit('customevent','work');
});
If the connect handler is not hit then verify that you are referencing the client side socket.io javascript library correctly (jade syntax):
script(type='text/javascript',src='/socket.io/socket.io.js')
Finally figured it out.
It was working fine on opera but not on chrome and firefox. I found this link in which the guy says to insert this code snippet on the server side.
io.configure('development', function(){
io.set('transports', ['xhr-polling']);
});
It's working fine now.

sessions not saved when socket.io starts

I have strange problem and I don't have any clue whats happening. Somehow sessions are not saved to redis anymore when I start socket.io, but when I comment out socket.io they work. The code can be found here: nothing unusual. This code stopped working after a db crash. When I tried to run the app again, it said that redis connection is already in use. I found and killed the node process that was using this connection, and I'm able to start my app again, but now there is this issue with sessions.
var config = require('./config')
, express = require('express')
, routes = require('./routes')
, RedisStore = require('connect-redis')(express)
, sessionStore = new RedisStore(config.redis)
, app = express.createServer();
app.configure(function () {
app.use(express.static(__dirname + '/public'));
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({
secret: config.sessionSecret,
key: 'express.sid',
store: sessionStore
}));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
})
app.configure('development', function () {
app.use(express.errorHandler());
});
app.enable('jsonp callback');
routes.init(app);
app.listen(config.port);
console.log("listening on port " + config.port);
// socket.io
var io = require('socket.io').listen(app);
io.configure(function() {
io.set("polling duration", 10);
io.enable('browser client minification');
io.enable('browser client etag');
io.enable('browser client gzip');
io.set('log level', 3);
io.set('transports', ['xhr-polling']);
}
);

Resources