每个客户端的套接字IO连接事件触发三遍

时间:2018-08-14 08:12:44

标签: angular socket.io

我在Angular 6应用中使用套接字IO进行实时通知。由于某种原因,每个客户端都会触发连接事件(和断开连接)事件三次。

我正在尝试跟踪在线用户,但这引起了问题。这是我的索引的相关部分。

const app = express(); // Initialize our app variable
const server = http.createServer(app); // Create HTTP server

// Set Port
const port = process.env.PORT || 3000;
app.set('port', port);

// CORS middleware for authentication
app.use(cors());

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Set Angular dist output folder as static folder
app.use(express.static(path.join(__dirname, 'dist')));

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
require('./server/config/passport')(passport);

// Send all other requests to the Angular app
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

// initialise database and listen on websockets
db.initDB(server);

以及db.ts中的套接字IO部分:

  const io = require('socket.io')(server);

  // DATABASE FUNCTIONS
  let activeUsers = [];
  let numUsers = 0;

  // Socket events
  io.on('connection', (socket) => {
    const clientId = socket.id;
    // Log whenever a user connects
    console.log('User connected');
    let found = 0;

    for (let i = 0; i < activeUsers.length; i++) {
      if (clientId == activeUsers[i].clientId) {
        found = 1;
      }
    }

    if (found == 0) {
      activeUsers.push({
        clientId:clientId,
        user:null
      });
    }

    numUsers++;
    io.emit('numUsers',numUsers);

    console.log(activeUsers);

    // Log whenever a user disconnects
    socket.on('disconnect', () => {
      console.log('User disconnected');

      numUsers--;
      io.emit('numUsers',numUsers);

      for (let i = 0; i < activeUsers.length; i++) {
        if (activeUsers[i].clientId == clientId) {
          activeUsers = activeUsers.splice(i,1);
          break;
        }
      }

      console.log(activeUsers);
    });

    // login
    socket.on('userLoggedIn', function(user) {
      console.log('USER LOGGED IN!!');
      console.log(user);

      for (let i = 0; i < activeUsers.length; i++) {
        if (activeUsers[i].clientId == clientId) {
          activeUsers[i].user = user;
          console.log(activeUsers);
          return;
        }
      }
    })

就像我说过我正在使用Angular 6并运行nodemon一样-我以为nodemon可能会引起问题,但是我尝试在没有它的情况下运行服务器,并且得到了相同的结果。我正在使用package.json中的npm run web启动客户端/服务器:

  "web": "concurrently --kill-others \"npm run tsc\" \"npm run client\" \"npm run server\"",
    "client": "ng serve --aot --proxy-config proxy.conf.json",
    "server": "concurrently \"tsc -p server --watch\" \"nodemon index.js\"",

0 个答案:

没有答案