Java – Query to get socket.io options in nodejs

Query to get socket.io options in nodejs… here is a solution to the problem.

Query to get socket.io options in nodejs

I created a chat application with android java as the client and node.js as the server side.

Client:

IO. Options opt=new IO. Options();
opt.query="token=anything";
socket = IO.socket("http://xxx.xx.xxx.xxx:PORT",opt);
socket.connect(); 

I want to send a token on connection and get it in the server for verification…
How can I get the token I pushed in opt.query in node.js?

If you have a good idea to send some data, such as a connection token or some work to secure the connection, pay attention.

Thanks

Solution
Server-side:

io.on('connection',function(socket){
console.log(socket.handshake.query.token);
});

Thanks @Marcos

Solution

You can access query options in Node.js via socket.handshake.query

const ws = io(http);

ws.use(async(socket, next) => {

try {
        await validateToken(socket.handshake.query.token));
        return next();
    } catch(e) {
        return next(new Error('Authentication error'));
    }

});

ws.on('connection', socket => {
      /* ... */
});

Related Problems and Solutions