Should I be using socket.io for my nodejs application? - node.js

I am learning HTML5 and doing so by building a simple chatroom using Express, PassportJS, Mongoose/MongoDB, connect-mongoose, NowJS.
Everything works perfectly, except for one big problem: I am having trouble authenticating NowJS.
The usual way of doing this is to read the "this.user.cookie" property server-side and parse the string. However, for some reason, cookies is not being sent back to the server. (details here: NowJS cookie field in this.user is empty) After a lot of googling, I think there are no alternative, secured, way for me to authenticate NowJS connections/clients.
Question
I am thinking of stripping all of NowJS out of my web app, and using socket.io directly. Is socket.io easy with work with? Would I lose key functionality if I switch to socket.io, instead of using NowJS?
Can I use socket.io to:
1) Call server-side functions?
2) Share server-side variables with the client?

Socket.io does not share variables or allow you to call server side functions. It allows you to bind and emit events on the client side and server side.
As for your cookie not being sent, its most likely that its being considered a cors, cross domain request, this can happen if your using a different port for socket.io then the http server that set the cookie.

Related

How use app.use in io.on?

How I can use app.use in socket.io? E.g.
io.on('connection', function(data){
app.use('uri here', function(req, res){
// emitting here
});
});
It's really?
I have:
ss1.example.com (head-server for caching online users with users servers).
ss2.example.com (first app server)
ss3.example.com (second app server)
You're misunderstanding something here. The sequence of events when a web page is loaded is as follows:
User initiates page load (by clicking on something or by typing something in the URL bar or by selecting a bookmark).
Browser parses the server, gets the host and port out of the URL and sends an http GET request for the path to the IP address for that host and port.
Web server receives the GET request and sends back to the browser an HTML page.
The web server may or may not use middleware when that request is received (depending upon what it wants to do).
Browser parses the HTML page and then runs scripts in the page.
Javascript in the web page runs and initiates socket.io connection to some host (often to the same host that the web page came from).
Web server receives socket.io request and socket.io handle recognizes the web request as a socket.io connection request.
Server-side socket.io code responds to client request for socket.io connection and a socket.io connection is initiated between browser and server.
Client or server can then send data over the socket.io connection.
Now, to your question about where to insert app.use(). That is for http middleware. You would insert that in the regular web server request chain, typically right before you app.get() and app.post() request handlers. You would not typically use http middleware for a socket.io connection.
If you wish to run some code before any socket.io connection connects, then you would use io.use() and use a socket.io middleware handler. That will give you access to the http request information on every socket.io connection request.
If you wish to run some code on every socket.io message that is received (regardless of the message name), that is not a supported feature of socket.io. There are some add-ons that hack into socket.io to allow you to essentially do a socket.on('*', ...) type event handler for all incoming socket.io messages, but that is not something that socket.io supports as a built-in feature.
If one of these options still doesn't sound like what you want, then please explain to use what actual problem you're trying to solve and we can better make a suggestion for that particular problem.
Note your question is a bit like an XY problem where you asked how to do what you think is the solution (using app.use() for socket.io) rather than describing the actual problem you want to solve. The problem with that type of question is that if you're wrong about the solution direction, then all we can really tell you is that you're wrong with that solution because you didn't describe the actual problem so we can direct you to the right type of solution. In the future, you will probably get better answers if you make sure to describe the problem you're trying to solve, not just the solution you're trying.

How to authenticate with express and socket.io with TOKENS and not with COOKIES.

I'm building a realtime mobile app (native) and I'm interested in starting the app from a user login screen and then move on.
I figured I need Express + primus with socket.io (or sockjs) + passport.socketio + redis (not 100% sure I need redis yet) to build my backend.
I even found this step by step tutorial which is really helpful, it takes me step by step to making a secure api.
My question is a double one:
How can I tweak this example to use TOKENS instead of cookies (since I'm building a native mobile app and not a browser web app) and its more secure according to this.
How to bind express with socket.io - in other words, how does socket.io get to know if the user is authenticated or not?
I welcome any comment or advice.
Thank you.
First, I would use a different websocket library instead of socket.io. The socket.io developers are currently working on engine.io and socket.io appears to not be very actively maintained. I've experienced many of the issues described in the following links and since moving to sockjs have not had any problems.
http://www.quora.com/Sock-js/What-are-the-pros-and-cons-of-socket-io-vs-sockjs?share=1
https://github.com/LearnBoost/socket.io/issues
https://github.com/ether/etherpad-lite/issues/1798
http://baudehlo.com/2013/05/07/sockjs-multiple-channels-and-why-i-dumped-socket-io/
You may have to implement your own custom events on top of sockjs, but that's pretty trivial. Since it sounds like you're already using redis then implementing rooms and pub/sub should be pretty easy too.
Here's how we do our token based socket authentication.
First the client makes an HTTP request to the server to request a token. This routes the request through express' middleware and gives you easy access to the session data. This is where you would interact with passport to access their account or session data. If the user is logged in then generate a UUID and store their session data in redis as a key/value pair where the key is the UUID and the value is their stringified session/account data. Only send the UUID back to the client.
When the client first creates a websocket connection set a flag on the socket that marks it as unauthenticated.
When a message comes in on a socket check to see if the socket is authenticated. If not then check for a token in the message. If it doesn't exist then kill the connection. If it does then query redis for the key/value pair keyed by the token. If redis returns any data then you now have the session data for that user and can attach it to the socket and mark the socket as authenticated. If there's nothing in redis keyed by the token then kill the connection.
Now when you perform any operations on a socket you should have access to the session data for that user.

socket.io : associate browser and computer with the connection

I am writing a game in node.js with socket.io library. It has a server to whom 2 clients connect and play. My game is working fine, but there is a problem.
If a client that is already connected connects again to the game it is considered as 3rd connection request which messes things up.
This usually happens when I restart my node server when client browsers were not closed. I do I get around this.
You can use cookies. There are modules for this: Socket.IO Authentication
But you can also do it manually, as it is a simple cookie:
When a user connects, add a step to identify the user before starting the game. This step should create a cookie or use the existing one and send it to the server for authentication.
It's not difficult, you can read and write cookies with javascript, and sending a String/number to the server is not a problem either (websocket.emit('auth',whatever)).
Based on this example, it looks like its possible to use cookies to identify sessions in socket.io, but you may be better off using query string values to identify a particular browser or computer:
https://www.exratione.com/2013/05/the-use-of-cookies-versus-query-string-tokens-to-identify-sessions-in-socketio/

Connecting to socket.io from pure js

Hi I looking for a documentation or example to connect to socket.io running on nodejs at server side from a pure JS from a client.
I have to remove the socket.io.js lib from the client side.
socket.io provides various transport layers. If you are happy to experiment and are sure that your client supports WebSocket in all cases, then you might be successful in reproducing the WebSocket-based part of the socket.io protocol on the client side. This, however, seems to be a tedious task compared to just using the code that you would re-invent (partly) anyway.
Use socket.io on the client side, or take an entirely different approach, also on the server side.

adding web socket chat into existing nodejs app

I've made nodejs application by this template. And now I want to add simple websocket chat.
My question is: do I have to completely rewrite that application to add websocket chat or I can to save that structure?
You can create a chat using Socket.IO (or another library), it's perfectly possible (and probably a best practice even) to separate the two: the regular server and the WebSocket server.
The two aren't tied together.
I have never used the express MVC template, but socket.io does not use express routes and from my experience they exist side by side just fine. Just add your socket.io server code to app.js to test it out and you can use the client side code within any of your express views.
This assumes you're using socket.io of course. I have no experience with other methods of using websockets with node.js.

Resources