put condition of time when a client disconnects to a socket server - socket.io

Hi everyone as a beginner in WebSockets i want to put a condition that will query when a client will be online or offline for such a time on my server node.js using socket.io
socket.on('disconnect', function() {
db.query("MY_SQL_REQUEST");
});
As a example when the user is disconnected for 10secondes it does the request. I think the solution is to use a loop if, but i dont know how to process after ...
If you need more informations about my code dont hesitate to ask
Thanks :)

when user online then you can store socket id in specific user.
when user disconnect then automatically call socket disconnect event and you will get disconnected socket id. once you receive socket id
you can update query for user offline using disconnected socket id.
socket.on('disconnect',function(){
console.log("socket disconnect called: ",socket.id);
db.query("MY_SQL_REQUEST"); // where socketId = socket.id
})

Related

How to determine the user (get access to his session data) in laravel by receiving a request through node sockets?

The site (laravel 6) has a page where we connect to the socket server in node (self-written sockets are used).
Node is just an intermediary between the client and laravel. Therefore, node then sends a post request to laravel with client data.
laravel needs to determine what kind of user it is, if everything is correct, then get access to its session data (do something with them, this is already business logic) and return confirmation of successful connection of this client to node.
If laravel has not defined the user, then returns to node a refusal to connect this client.
The question is how, with such a bunch, to determine in laravel what kind of user wants to connect?
It is possible to pass the encrypted session id stored in the user's cookies from the client to node and forward it to laravel. And how to start this session in a standard way and work with it?

How to send to only one client and not all clients using Go and gorilla websocket

I am trying to learn websockets with Go. I have been looking at examples with gorilla websocket.
I have checked out these 2 examples that show how to use gorilla websocket:
https://github.com/gorilla/websocket/tree/master/examples
https://www.youtube.com/watch?v=ysAZ_oqPOo0
All of these examples show how to connect to a websocket server, send and receive texts. But what I don't understand is how you can send to only one client. Because in a real world application you will have users, and we don't want all users to receive the same message and same data. Is there a way for me to get the unique id of a connection which I can save in a database like redis and link it to a user id in the same database, and then use that websocket id to send back to a specific client if that user id received a message or a notification? Is this how one would go about and achieve something like this? If that is the case, how would I that?
Is there a way for me to get the unique id of a connection which I can
save in a database like redis and link it to a user id in the same
database, and then use that websocket id to send back to a specific
client if that user id received a message or a notification?
Sure! You can generate Id by yourself while user registering. Just add userId field in connection structure
In chat example you have hub, which contains connections pool. That pool is using to broadcast messages to all users:
case m := <-h.broadcast:
for c := range h.connections {
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
}
}
}
So there you go. You should make method to send private message, depend on userId

opening modal from server side, grails

I am trying to show modal after session expired. I am using filters to catch that session has expired:
def filters = {
all(controller:'graphs', action:'*') {
before = {
if (session.expired) {
//some code to invoker modal
return false
}
}
}
}
Modal should notify the user that session has expired and redirect to main page. Any suggestions on how to invoke modal?
What you are proposing is very tricky to implement because you need a client-initiated request or session to transmit anything to the client and any such request will prolong the session. I see two possibilities:
Polling
If you don't mind the session being prolonged and just want to make sure the user is still logged in the simplest way would be to implement Javascript polling using setInterval or similar (but make sure the polling stops on first failure or users are at risk getting redirected to the polling endpoint after logging in again, especially if they have more than one tab open). If you don't want to stretch the session you could try a hacky workaround.
Websockets
You could open a websocket connection using an appropriate plugin and keep it open. You need to make sure no session prolonging heartbeats are being sent. Then when the session ends, send a message back through the connection. Note that this will involve more work than polling.

Meteor _lastSessionId is always different for the same tab

I'm experiencing something a bit odd and I can't make heads or tails of it... I'm using Meteor to send the sessionId to from the client to the server but on every refresh of the page, the sessionId I get is different, which shouldn't be, am I correct?
Client
Meteor.call('logSession', Meteor.default_connection._lastSessionId);
Server
Meteor.methods({
logSession: function(sid) {
console.log(sid);
}
})
Any reason why the sid is always different?
Thanks!
The _lastSessionId is created for each websocket session between the client and server. It represents the websocket's session & state on the server side and not a cookie or something persistent.
When you refresh/open a different tab a new websocket would be created and this is why the session id is different.
Each Session ID represents the state of the data the client has on the server. This means the server 'knows' what data the client has on each session depending on the subscriptions so that it knows what to send down & what to change if something changes, for that particular tab.
When you refresh the page, you're using using a fresh new state so Meteor doesn't attempt to reconnect using a previous session id and restore your previous state, because there isn't a need to resume a previous state in terms of subscriptions since the user would expect the page to be fresh.
If you want to use some form of persistence available along tabs such as cookies use localStorage instead:
localStorage.setItem("foo", "bar");
console.log( localStorage.getItem("foo") );
=> "bar"

node.js Express/socket.io hybrid application with facebook

I am using express/socket.io combination in my node.js app. So far it's working fine.
Now, I need to store facebook user id and email id (after user being authorized) into session scope. I see there are lot of options and a bit lost here.. in my app, most of the communications happen through socket.io.. ultimately what i want is to access user id and email id anytime in the client side...
var express = require("express"),
fs = require("fs"),
app = express.createServer(
form({ keepExtensions: true })
),
io = require("socket.io");
socket = io.listen(app);
After being authorized, I suggest using the accessToken which is already in the cookies and then sending it through the socket.io and fetching the email and the id using graph.facebook or your own DB. The problem with storing user ID and Email is that it could insecure, since session hijacking could happen.
Facebook has its own experts on security to make sure it wouldn't be hijacked. Use it!
This might help:
http://criso.github.com/fbgraph/
After being authorized you can store the data in your session via express
http://expressjs.com/guide.html#session-support
On a very basic level:
// Get data from facebok and store it on a var `userData`
// server
socket.on('getUserData', function (callback) {
callback(facebookUserData);
});
// client
socekt.emit('getUserData', function(userData) {
console.log(userData);
});

Resources