Socket.io Express 3 sessions - javascript

Is there a good way of using sessions with Socket.io in Express 3.0? A way of getting the clients' session id in a safe way? So that I can send notices to members specific to their account and make private chats from member to member?
I'm using MySQL store in Express 3.0

I wrote a tiny module to abstract it, here's how its usage looks like. It was written and tested using express 3, socket.io 0.9.10 and the (default) MemoryStore from connect 2.4.5. It should work fine with other compatible stores.
var SessionSockets = require('session.socket.io')
, sessionSockets = new SessionSockets(io, sessionStore, cookieParser);
sessionSockets.on('connection', function (err, socket, session) {
//your regular socket.io code goes here
});
For more details on how it works see https://github.com/wcamarao/session.socket.io
You might want to pay attention to the part of the README where it says how to use it with your own session store key (I'm assuming your mysql store uses a name other than the default 'connect.sid').

You should check out express.io, a very simple micro-framework for express and socket.io integration. It handles express and socket.io sessions automatically.
npm install express.io
Check out the session support example here:
https://github.com/techpines/express.io/tree/master/examples#sessions

I did something slightly different to get it working. I read through a lot of posts on nodester github and came with the following solution....
Replace:
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
with:
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require('socket.io').listen(server);
My plan is to continue with this workaround until issues around express3 and socket.io are resolved.

Related

Unable to connect from a different network express.js

I'm experimenting with node.js and express.js.
When I try to connect to my web server from any computer in my network, it works, but then when I try to connect from outside network the connection times out.
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res) {
res.send("Hello World");
});
http.listen(3000, '0.0.0.0', function() {
console.log("Listening on port 3000!");
});
I just tested your code and I'm able to access the server from outside my local network by navigating to:
http://173.0.[my].[ip]:3000
So the code is correct. It could be that you need to open the port 3000 to the outside world. Here's how it can be accomplished.
Through your router admin interface
Here's mine for example:
Where 192.168.1.130 is the local IP of the PC I'm running the http server on.
Don't forget to click the Save settings button in that interface to apply the changes.
Using a tool like ngrok (mentioned by eddiezane)
Install ngrok through their website or without leaving the command prompt, with the ngrok node wrapper.
npm install ngrok -g
Start your http server and then run:
ngrok http 3000
Navigate to one of the url in front of Forwarding:
The free version is more for a quick test and less as a definitive way to expose a service in a production environnement since every time you restart ngrok, a new user-hostile url is given to you.
Other possible problems
It could also be that you need to add an exception to the firewall (if on windows).
To add to Emile's answer, I would check out ngrok which is an awesome tool that generates you a publicly accessible URL for a port on your local machine.
Here's a good blog post on it my buddy wrote.

Nodejs on VPS only running on my network

Nodejs server which is installed on my VPS is accessible only on my network. People from outside world cannot access it. If its online, it should either be accessible all over the world or nowhere. What to do?
Code in my js file:
var app = require('express')();
var http = require('http').Server(app);
// Also tried http.listen(3000, "0.0.0.0", function(){
http.listen(3000, function(){
console.log('Server listening to port 3000');
});
Well, in your question you say that you want the Node app to be accessible to everyone in the world, or nobody at all. If you're VPS provider restricts you to only running things on an internal network, however, then it is impossible to do what you are asking.
The network rules will simply not allow it.
With that said, however, I'm going to make a recommendation for changing your Express application. Here's how it should look:
let express = require('express');
let app = express();
app.listen(3000);
The code above will bind your Node application to port 3000 in the simplest way possible using Express directly. This is probably what you want.
Also: please note that if you are intending to build a public service, you will need to likely do one of two things:
Bind your Express server to port 80 (for HTTP), or
Use a web server to proxy requests from port 80 (HTTP) to port 3000 (local).
My bad adding the site's IP as the second parameter of listen function solved it.
http.listen(3000, "xx.xxx.xx.xxx", function(){
console.log('Server listening to port 3000');
});

Socket.io in Express routes file

I'm working on a project which consists in creating a game of the goose like. In order to do that, I'm using Node.js, Express, jade and now Socket.io. But I encounter some trouble, like, in example, to share the position of one client to the other client. Because my variable position is in a function in index.js and I don't know how I can use Socket.io in a route file. I try some things, but nothing works.
On internet, I've seen some people who say that there is no-sense to use Socket.io in an express route file. So how can I do that ?
In my index.js I've that :
exports.deplacement = function(io)
{
return function(req,res)
{
//[...]
io.sockets.on('connection', function(socket)
{
socket.broadcast.emit('position', space);
});
res.render('moteur' //[...]);
}
}
And in my moteur.jade I've done this :
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');
socket.on('position ', function(space) {
alert(space);
})
First of all, I'm not sure what your question exactly means, but if it is what I think it is then I think what you mean by using socket.io in a route file is to be able to include the client side javascript lib provided with socket.io module of Node.
In order to do that, you have to allow the socket.io module to listen to server. This works like a middle-ware itself. Everything has to go through socket.io first before they are routed to the server. So, when you request the client side lib, it is uploaded to the client.
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server)

Run NodeJS app on appFog

All I want to do is deploy my little nodeJS app onto the free hosting site, appFog.
Nomatter what ports I set on my client side or on my server side.. I consistently get the error message:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^ Error: listen EADDRINUSE
When this is on my laptop / desktop running on localhost, everything works just fine.
So this is what I've got going on:
Client side:
this.connection = new WebSocket('ws://super1onate.aws.af.cm:1337');
Server Side:
var express = require("express"); // load the express module
var app = express(); // App now holds the server object
// What ports to listen on
app.listen(process.env.VCAP_APP_PORT ||1337);
server.listen(process.env.VCAP_APP_PORT || 1337, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort); });
Your server code looks ok. What is events.js? It looks like maybe you're including a module that's trying to bind to a port it shouldn't.
Once you get your server running, I don't think your client code will work. As far as I can tell, AppFog doesn't support websockets, and if it does, you'll probably want to hit port 80, not 1337.
Alright, I'm going to answer my own questions.
AppFog does not support WebSockets. websockets =/= socket.io btw fyi
Anyways, according to this site:
http://feedback.appfog.com/forums/171983-appfog/suggestions/3543100-add-websocket-support-to-node-js

Using connect-session middleware with Redis in Locomotive framework

I am using Locomotive framework for creating a nodejs web-application.
In config/environments/all.js I have:
var express = require('express')
, poweredBy = require('connect-powered-by')
, util = require('util')
, connectAssets = require('connect-assets')
, redis = require('redis')
, RedisStore = require('connect-redis')(express)
, sessionStore = new RedisStore();
........
........
this.use(express.cookieParser());
this.use(express.bodyParser());
..........
..........
this.use(express.session({
secret: 'LoremIpsumDolorSit_Amet',
store: sessionStore
}));
However the session object is not present in the request object. ie. in a controller instance:
this.req.session is undefined. What am I missing and How do I configure the connect-session middleware to use redis data-store ?
My redis server is running on default port and it shows a client connected when I run my server. The client gets disconnected only when I terminate the server.
I am using Node 0.6.18, redis server version 2.4.8, locomotive version 0.3.3 and express 3.0.4 on Fedora 16.
For sessions to work in express, the three of the following must be in this very order:
this.use(express.cookieParser());
this.use(express.session(...));
this.use(this.router);
In my implementation, I had the third statement above the second.
Apparently, this is a known idiosyncrasy with Express and I am not informed enough about the inner workings of Express to explain why this is the case. Probably someone who has more experience with NodeJS can elaborate on the details.
With this.use(), you add middleware to Express' request/response handling: incoming requests pass through all middleware before ending up at your application, and outgoing responses go back up the middleware chain before being sent back to the client.
The order in which you install middleware matters: if you have one middleware (like express.session) which depends on another middleware (like express.cookieParser, to parse session cookies), you install the dependency first.
In most cases, this.router should be installed last, or almost last (usually followed by an error handling middleware), because it depends on cookies and sessions having been handled before it get called.

Categories

Resources