Socket.io my middleware for custom Id does not works

爱⌒轻易说出口 提交于 2021-02-11 12:10:05

问题


i followed instructions in this link Rohit Nishad and my data is well passed from client to server. But the ID is not passed from my middleware with the overwritten function. A new Generated ID is shown on socket.io connection.

Any idea what's going wrong please ?

I'm using socket.io v3.1.0

server.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

const socketIO = require('socket.io');
const io = socketIO(server, {
    cors: {
        origin: "http://localhost:4200",
        methods: ["GET", "POST"]
    },
});


// Socket.io configuration
io.of('/notification').use((socket, next) => {
    console.log('(socket.handshake.query.userId) :', socket.handshake.query.userId);
    io.engine.generateId = (req) => {
        socket.handshake.query.userId;
    };
    next(null, true);
});

io.of('/user').use((socket, next) => {
    io.engine.generateId = () => socket.handshake.query.userId;
    next(null, true);
});

io.of('/notification').on('connection', socket => {
    console.log('[Notification] - New client connected : ID ', socket.id);

});
io.of('/user').on('connection', socket => {
    console.log('[User] - New client connected : ID ', socket.id);

});


const serverPort = process.env.PORT || port;

// Launch server

server.listen(serverPort, () => {
    console.log(`App is running ! Go to http://${host}:${port}`);
});

and console output:

App is running ! Go to http://localhost:3000
(socket.handshake.query.userId) : 5ffdb966c204c85d4061bf9f
[Notification] - New client connected : ID  EjdB0uz8K7NSGWYyAAAB
[User] - New client connected : ID  E4tu9sKXliWTFEcsAAAC

来源:https://stackoverflow.com/questions/65833164/socket-io-my-middleware-for-custom-id-does-not-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!