如何在我的node.js中添加以下代码而不破坏其他代码?

时间:2018-04-30 12:37:22

标签: javascript node.js

所以我在node.js服务器中有以下代码,

var socket = require( 'socket.io' );
var express = require( 'express' );
var https = require( 'https' );
var fs = require('fs');

var app = express();

var privateKey = fs.readFileSync('', 'utf8');
var certificate = fs.readFileSync('', 'utf8');
var credentials = {key: privateKey, cert: certificate};

var server = https.createServer(credentials, app );

var io = socket.listen( server);
io.set('transports',['xhr-polling']);
io.sockets.on( 'connection', function( client ) {
    console.log( "New client !" );

    client.on( 'message', function( data ) {
        console.log( 'Message received ' + data.name + ":" + data.message );
        //client.broadcast.emit( 'message', { name: data.name, message: data.message } );
        io.sockets.emit( 'message', data);
    });

    client.on( 'doTrade', function( data ) {
        //console.log( 'Message received ' + data.name + ":" + data.message );
        io.sockets.emit( 'doTrade', data );
    });
});

server.listen( (x) );

我想添加以下内容以显示已连接用户的数量。

io.sockets.on("connection", socket => {
  let clientCount = io.engine.clientsCount;

  io.sockets.emit("user count", clientCount);
  socket.on("disconnect", () => {
    io.sockets.emit("user count", clientCount);
  });
});

https://juandiego.co/blog/show-connected-users-socketio-vuejs/

直接添加时,由于双重调用“连接”,它会破坏其他组件?

我如何正确整合这个?

0 个答案:

没有答案