Node.js: Receive events from browser - node.js

How do I receive events from the browser in my node.js code? (e.g: I imagine Mixpanel, kissmetrics, etc do something like this?
thanks

The same way any other web server receives events from the browser: the browser makes an HTTP request to the URL of your server and the server receives that request. Listening for HTTP requests is the "Hello World" example for node.js.

What you're looking for is http://hummingbirdstats.com/ realtime stats 20 times a second.
You should also checkout socket.io if you haven't. Websockets events are faster than HTTP requests.

You have to send them to your server, via AJAX or some similar method.
Remember, node code runs on the server; the browser runs on the client. The way to get information back and forth from a server to a client running a web browser is an HTTP request.

I recommend dnode. Search for dnode on the browser in the README. It's a quick and complete example of making a RPC. In this case the remote function would be an event handler.
It uses socket.io, which supports websockets, flash sockets, and xhr.

Related

When we use http.createServer() in Node.js

I just started learning Node.js, and I'm wondering when developer should/need to use http.createServer()
My process of thinking is: "When I want to catch data from server I use: http.request and http.get methodes.

When I want to POST on server I will use http.request with POST method options parameter.
I just can’t figure out, when I should use http.createServer() method?


If I work on remote server (server is already exists).
I red documentation: This class is used to create a TCP or IPC server.
w3School says: The http.createServer() method turns your computer into an HTTP server.
If you can, give me comprehensive explanation with real world example.
Thanks
When you use something like http.request(), you're connecting to another HTTP server and requesting data from it. If you wanted to be that server yourself, you would need to use http.createServer() to do that.
For example, a common use case of Node.js is to create an API server that receives HTTP requests from web pages and fetches or manipulates data in a database. It takes the resulting data and sends it as an HTTP response.
The Node.js documentation you read seems to be for net.createServer(). While http.createServer() does create an underlying TCP server, it also accepts a callback for listening for HTTP requests.
See also: https://nodejs.org/api/http.html#http_http_createserver_options_requestlistener

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.

Nodejs: SocketIO (websockets) vs Http

Normally i use ajax http requests to get/post data. Now i have thoughts like why shouldn't i replace all the ajax get requests with socketIO?is there any disadvantage in following this approach?
I understand that session cookies via http headers will be sent between client and server during every http requests, during client<=>server interactions using sockets, will the session cookies in browser automatically sent to the server via socket headers(if that exists)?
In which usecases should i prefer SocketIO over Http?(if you consider this as a question that demands broad answer then you can link me to some relevant articles)
WebSockets are useful when the server needs to push some real time information to the client about some events that happened on the server. This avoids the client making multiple polling AJAX calls to verify if some event has occurred on the server.
Think of a simple chat application. If the client needs to know if the other participant in a chat session has written something in order to display it, he will need to make AJAX calls at regular intervals to verify this on the server. On the other hand WebSockets allow the server to notify the client when this even occurs, so it is much more efficient in terms of network traffic. Also the WebSockets protocol allows the server to push real time information to multiple subscribed clients at the same time: for example you could have a web browser and mobile application subscribed to a WebSocket and talking to each other directly through the server. Using AJAX those kind of scenarios would be harder to achieve and would require much more stateless HTTP calls.
I understand that session cookies will be sent between client and server during every http requests, is this case the same during client<=>server interactions using sockets
The WebSockets protocol is different from the HTTP protocol. So after the initial handshake occurs (which happens over HTTP), there are no more notion of HTTP specific things such as cookies.
There's one important thing that you should be aware when using WebSockets: it requires a persistent connection to be established between the client and the server. This could make it tricky when you need to load balance your servers. Of course the different implementations of the WebSockets protocol might offer solutions to this problem. For example Socket.IO has a Redis implementation allowing the servers to keep track of connected clients through a cluster of nodes.

Pure socket logic

I have a nodejs app, and every client has an open socket connection, the reason i am using sockets because I need to update the data on the client whenever the data in the database changes by an external process.
However every other operation in my app doesn't require a socket connection and mostly initiated by the client (CRUD operations), But i am confused about one thing since I always have an open socket connection, wouldn't it be better to use that socket connection for every operation and make the app with pure socket logic?
When using websockets maybe it's fine. But if socket.io switches to XHR (AJAX) transport it might be irrational.
Take a look at the differencies of these two approaches:
In case of simple AJAX (without socket.io) when you want to get some info from server, or change something on a server, you send GET or POST request,
and server responses. Everything's fine.
But in case of socket.io (XHR transport) there is one request to send data, and another to get the response.
(You can make your own experiment - write io.set('transports', ['xhr-polling']); and try to send data to the server and make server respond -
you will see 2 AJAX requests in the Network tab)
So instead of one AJAX request socket.io makes two requests.
This is not because socket.io is bad. This is a feature of sockets approach. This approach is good if you want one side (client or server) to send messages independenly from the other. This is what socket.io does very good.
But if you want to do "request-response" stuff it's the best to use simple AJAX because of traffic economy (note that I compare simple AJAX to socket.io AJAX. Websockets - is another story).
But since this question is about approaches and can't have 100% "yes" or "no" answer, there are might be different opinions.
Sorry for English. I tried to write as clearly as I could :)

node.js SPA webapp - all communications via websockets

I have a SPA application (Backbone on client and node.js on server). It all communication in both directions is through via websockets. Now I wondered - it's a good idea? What are the cons before approach: the client sends data to the server via the REST API, and server sends data to client via websockets?
thanks.
UPD:
I have websockets in any case because my app is multiroom chat.
Even if you only consider RPC ("Remote Procedure Calls"), REST is less capable than WebSocket.
REST, since it runs over HTTP, cannot pipeline RPCs. Each HTTP connection can only serve 1 RPC synchronously. And browsers limit the number of parallel HTTP connections to a given origin.
With RPC over WebSocket, you can fire off 100 RPCs pipelined, and process RPC returns asynchronously as they come in.
Then, with WebSocket, you can have server-initiated notifications as well. E.g. you can have full-flavored Publish & Subscribe.
WAMP ("The Web Application Messaging Protocol") runs over WebSocket and was designed exactly for this: SPAs that need 2 messaging patterns in 1 protocol - RPC and PubSub.
Disclaimer: I am original author of WAMP and work for Tavendo.
If server needs uncertain time to prepare data, it may be a good idea though
basically there is no reason to use websocket(socket.io) for REST API.
because of what REST API stands for,You don't have to keep connection stablished nor don't have to wait for someones action like broadcasting server.
EDIT answering the comment
even if you already used websocket,it doesn't mean you can't handle normal req/res.
RESTapi with websocket is like
get request -> server response -> client try io.connect(); -> connection established -> server send data to the client thru websocket
and normal REST API is like
get request -> server responce
which do you choose?

Resources