Socket.io连接多次连接,我认为应该只是一次

时间:2019-02-04 22:50:30

标签: node.js socket.io

我已经根据wes bos的课程构建了一个webapp: https://github.com/wesbos/Learn-Node/tree/master/stepped-solutions/45%20-%20Finished%20App

现在,我想添加一个简单的消息传递系统,所以我正在尝试添加socket.io

在他们的网站上:https://socket.io/get-started/chat/,他们建议使用以下代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

所以在我的start.js文件中,我试图使其适应上面的代码,并且部分起作用,只有在他们的网站上它说它应该只为每个连接的用户记录一次。

在我看来,它像每帧一样记录。

有什么想法吗?

这是我的start.js

const app = require('./app');
app.set('port', process.env.PORT || 7777);

const server = app.listen(app.get('port'), () => {
  console.log(`Express running → PORT ${server.address().port}`);
});

// const http = require('http').Server(app);
const io = require('socket.io').listen(server);

io.on('connection', function(socket){
  console.log('a user connected');
});

编辑:这也是我的ap.js:

// create our Express app
const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views')); // this is the folder where we keep our pug files
app.set('view engine', 'pug'); // we use the engine pug, mustache or EJS work great too

// serves up static files from the public folder. Anything in public/ will just be served up as the file it is
app.use(express.static(path.join(__dirname, 'public')));

// Takes the raw requests and turns them into usable properties on req.body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// Exposes a bunch of methods for validating data. Used heavily on userController.validateRegister
app.use(expressValidator());

// populates req.cookies with any cookies that came along with the request
app.use(cookieParser());

// Sessions allow us to store data on visitors from request to request
// This keeps users logged in and allows us to send flash messages
app.use(session({
  secret: process.env.SECRET,
  key: process.env.KEY,
  resave: false,
  saveUninitialized: false,
  store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

// // Passport JS is what we use to handle our logins
app.use(passport.initialize());
app.use(passport.session());

// // The flash middleware let's us use req.flash('error', 'Shit!'), which will then pass that message to the next page the user requests
app.use(flash());

// pass variables to our templates + all requests
app.use((req, res, next) => {
  res.locals.h = helpers;
  res.locals.flashes = req.flash();
  res.locals.user = req.user || null;
  res.locals.currentPath = req.path;
  next();
});

// promisify some callback based APIs
app.use((req, res, next) => {
  req.login = promisify(req.login, req);
  next();
});

// After allllll that above middleware, we finally handle our own routes!
app.use('/', routes);

// If that above routes didnt work, we 404 them and forward to error handler
app.use(errorHandlers.notFound);

// One of our error handlers will see if these errors are just validation errors
app.use(errorHandlers.flashValidationErrors);

// Otherwise this was a really bad error we didn't expect! Shoot eh
if (app.get('env') === 'development') {
  /* Development Error Handler - Prints stack trace */
  app.use(errorHandlers.developmentErrors);
}

// production error handler
app.use(errorHandlers.productionErrors);

// done! we export it so we can start the site in start.js
module.exports = app;

1 个答案:

答案 0 :(得分:1)

您需要删除以下行:

const server = app.listen(app.get('port'), () => {
    console.log(`Express running → PORT ${server.address().port}`);
});

您正在这里听,但是您应该这样做:

const http = require('http').Server(app);
http.listen(3000, function(){
  console.log('listening on *:3000');
});

或通过Express设置端口的情况:

const http = require('http').Server(app);
http.listen(app.get('port'), function(){
  console.log(`Express running → PORT ${server.address().port}`);
});

更常见的语法是将port声明为const:

const PORT = 7777
const http = require('http').Server(app);
http.listen(PORT, function(){
  console.log(`Express running → PORT ${PORT}`);
});

依次将您的socket.io服务器创建为:

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

按目前的情况,您可以(据我所知)创建两个服务器。

编辑:

您的整个start.js应该如下所示:

const app = require('./app');

app.set('port', process.env.PORT || 7777);

const http = require('http').Server(app);

const io = require('socket.io')(http)

io.on('connection', function(socket){
    console.log('as user connected' + Math.random());
});

http.listen(app.get('port'), function(){
    console.log(`Express running → PORT ${server.address().port}`);
});