How can i use socket.io globally in node.js - node.js

Currently I am using an API to get chatList, so the user cannot know if they have received a new msg. They have to refresh the page in order to know that there is a new message.
I am connecting with the socket when the user is in chat and they get disconnected with socket when they leave chat and move to some other page.
But I want them to stay connected if they move to some other page.
Can you please guide me how can I achieve that? Is there any general socket available for applications ?

socket.io and webSocket connections cannot survive from one page to the next. When you leave one page and go to another, all resources from the first page (including any webSocket or socket.io connections) will be closed. That's how the browser works.
You can make a single page app (SPA) where the user clicks on things and the view changes, but it's just loading dynamic content into the same page so the actual web page never closes in the browser and thus the socket.io connection can persist.
Or, you can tag the user with a cookie so that when they leave the page, their connection closes and then they load another page and a new connection is established, your server can see that they are the same user that was just connected and your server can set things up appropriately for them to continue as if the connection was never redone.
Is there any general socket available for applications ?
No, there is not.
I am connecting with the socket when the user is in chat and they get disconnected with socket when they leave chat and move to some other page.
Yes, all browsers disconnect when the web page closes.

Related

Socket.io keep the connection on client side when client refresh or open new page

Have some way to keep the same socket.io connection on client side if user open a new page or refresh the page, maybe store the socket in session or it's impossible?
It's impossible. You cannot keep the same socket.io or webSocket client connection when the page is changed or refreshed. The browser simply does not do that. When a new page is loaded or the current page is refreshed, all resources from the previous page are closed and freed by the browser, including socket.io/webSocket connections.
So, your server has to expect a new socket.io connection from the newly loaded page. If you use cookies or a server-side session object, you can identify, on the server, when a connection is coming from a client that you have previously seen and the server can then act accordingly to realize that this is just a previous client reconnecting on a new page.
It seems now that WebWorker are a more widespread technology that it could be use to share websocket.
As explain in this article https://crossbario.com/blog/Websocket-Persistent-Connections/
Webworker are Javascript that is running outside the "thread of the page" and thus are not deleted on page change.
Note that it is running only in the same domain.
You can also look at Kanaka's answer here How to maintain a WebSockets connection between pages? (2012-2017 answer beware)

How socket.io disconnect works?

Socket.IO timeout (disconnect) occurs if there are no activity present in the socket, but how is detected that are no activity? I dont find information about that. How works the detection process? For example:
If user closes the website tab, occurs disconnect?
There is any way user loses connection and disconnect will not be executed?
Is possible cache information informs that Im online even if I leave the website?
If you open your browser's developer tools in the network panel, you can filter your requests to ws requests (web socket requests), in there you can see your active web sockets connections. If you choose one connection, you can see the headers, the frames, the cookies and timing. If you choose the frames option you can see what's being sent and received, between your browser and your web socket server.
The next image will make it clear for you, it's chrome's developer tools:
Now in there you can see there are some numbers, basically your browser and your server are doing ping pong. You can read more about these numbers in this answer SocketIO Chrome Inspector Frames
This ping pong is what keeps the socket alive so we know that there are no timeouts. As for the disconnect and the connect I advise you to read more about the WebSockets API, in there you can see there are event listeners for onclose, onerror, onmessage and onopen.
So answering this question:
For example: If user closes the website tab, occurs disconnect? There
is any way user loses connection and disconnect will not be executed?
No, the onclose event will be fired, but even if any cosmic reason the onclose isn't fired you will eventually disconnect due to timeout.
As for your other question:
Is possible cache information informs that Im online even if I leave
the website?
Yes, that's not up to sockets, that's up to you and your implementation. You can keep a list of online users and only update that list from time to time, let's say 10 minutes. You can keep the online users lists and between the time you update your online users list, some of them are already disconnected.

How can I keep a socket connection alive going from 1 window to another?

I am fairly new to socket.io but am really enjoying getting stuck into it. I am using MEAN stack and have started to play around with socket.io. I have found that the socket connection is connected to the window, so when a refresh is done, the connection is dead.
With that said, I am trying to implement a simple chat feature, similar to the one they show on the socket.io getting started tab, fairly easy. However, my connection has been created before I click on this chat button. I want the chat window to open in a new window, and provide a chat for the previously connected individuals. Is this possible and how could I implement such functionality?
I am asking from a planning point of view really so not posting my code here. My code is very similar to that of the Hello World socket.io chat app, but I just want to maintain connection from one window to the next.
You cannot keep a socket connection open when you load a new page into that window. The connection belongs to a particular page and when that page is no longer active, the socket it closed and cleaned up by the browser (along with all other HTML/JS resources). Your new page should just open the socket again and you can use some sort of cookie to identify the new connection as the same user.
Another strategy is to not load a new window and use Ajax to load new content into the current window. This would allow you to keep the current socket alive.

How do I distinguish between and restore two different client socket connections from same user on server restart?

Imagine this scenario:
A client opens a browser tab and navigates to page-x. When the client is on this page, I emit some data via socket related to this page. Let's call this socket-context-x.
Then, client opens another browser tab (without closing the first one) and navigates to page-y. He connects with a new socket id. I start emitting different data when the client is on this page. And let's call this socket-context-y.
Now, imagine server is restarted and client's tabs auto-reconnect to the server. Now, I have to remember the contexts for each of these tabs that had socket connections so I can resume emitting relevant data to each page.
How would I distinguish the socket-context that each tab was on?
I cannot use session ids since session id would be the same for both tabs. I cannot use socket ids because after the server restarts and when clients auto-reconnect, new socket ids will be given.
I solved this problem by emitting an event on connect callback in the server when browser reconnects such as socket.emit("tellMeYourContext", null). Then, clients listening to this event send me the context they are in by doing socket.emit("resumeContext", contextObj). Then, I know what context each client and its tabs are on and can resume the spew accordingly.
Thanks #laggingreflex for inspiration.

Question regarding browser behavior when a response is sent from a server

Scenario:
The browser submits a HTTP request to a server.
The user simultaneously clicks on a bookmark or on another link on the page resulting in a new request to the server.
The server now sends back two HTTP responses (or the browser gets responses from two servers).
How does the browser decide which of the responses to actually process?
I know what will happen - am trying to understand why. Any references or websites that explain this would also be much appreciated.
Thank you,
vivek.
Edit: Saw this similar question after asking. Please merge/delete if appropriate.
The short answer to your specific question is that receiving a server's response (within a browser) is different from receiving a browser's request (within a server). When the browser opens a new connection to the server, what it's doing is creating a socket and then calling connect and send on that socket. When the server gets this incoming connection, it might not care if this is the same client as some previous connection. If does care (e.g. it has logged-in sessions or shopping carts) it has to use cookies or whatnot if to associate this connection with previous ones. (I'm ignoring persistent connections, which are beyond the scope of your question.)
But when the browser receives the response from the server, it does so by calling recv on the same socket that it used to send the request, so it knows which request that response goes with before it even starts reading it. In theoretical terms, the browser is maintaining state information about the connections it has open. In practical terms, it has a list or array of sockets.
The browser also keeps track of which windows and tabs are associated with which sockets. This is how it can update the spinners and status lines to reflect the status of the corresponding connections. And if the user clicks the stop button, it knows which socket (or sockets) to close.
So in your scenario, the user has clicked a link or bookmark in a window or tab associated with an existing socket representing a connection to a server where the server's response hasn't been received yet. The browser can simply close that socket as if the user had clicked the stop button. And even if it didn't close it, the browser knows the user no longer wants to see the response. Meanwhile it opens a new socket to the server the user is interested in.

Resources