如何在Node / Express路由和Socket.io之间进行通信

时间:2016-12-16 19:47:30

标签: node.js express socket.io

我想使用socket.io来跟踪应用程序的每日活跃用户。我的套接字连接如下所示:

let visitorData = {};

io.on('connection', (socket) => {
    socket.on('user', (data) => {
        visitorData[socket.id] = data;
    })

    socket.on('disconnect', () => {
        delete visitorData[socket.id]
    })
})

我希望能够将现有的Node / Express 路由和收到的数据合并到套接字连接中。特别是,我如何处理POST到/login端点以将登录用户名与套接字ID连接相关联。

例如:

app.get('/login', (req, res, next) => {
  const someSocket = /* socket */
  const someSocketId = /* socket id */;

  visitorData[someSocketId] = req.body.username;

  someSocket.emit('user', visitorData);
})

有没有办法将socket.io合并到Node / Express路由中,以便(a)将用户与来自请求/响应主体的socket.id和(b)emit信息相关联?

1 个答案:

答案 0 :(得分:2)

我使用passport socket.io设置了类似的内容。它创建了允许您从套接字访问用户的中间件。以下是我的一些实现:

Setup_next_toolbar

app.js

import GameSocket from './lib/game-socket'; var app = express(); GameSocket(app, 3700);

lib/game-socket.js

要使用此功能,您需要使用会话存储。我个人使用了redis会话商店connect-redis。这是在import Server from 'socket.io'; import passportSocketIo from 'passport.socketio'; import cookieParser from 'cookie-parser'; // Configured redisStore for authentication import {redisStore} from '../lib/session'; // Configured passport strategy for authentication import passport from '../lib/passport'; export default function GameSocket(app, port) { // Setup socket var server = new Server(); var io = server.listen(app.listen(port)); // Setup authentication io.use(passportSocketIo.authorize({ key: 'connect.sid', secret: 'your_secret', store: redisStore, passport: passport, cookieParser: cookieParser, success: (data, accept) => accept(null, true), failure: (data, message, err, accept) => { console.log(err); if(err) throw new Error(message); } })); // On connection listener io.sockets.on('connection', function (socket) { // This is an example of getting user info from the socket console.log('Success: New connection with: ', socket.request.user.username); // Add your socket events here }); return io; }

中配置的