socket.io在express中,怎么把io传到routes/index.js里去?
发布于 12 年前 作者 charje 8872 次浏览 最后一次编辑是 8 年前

这是app里的

var server = http.createServer(app);

var socket = io.listen(server);

server.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});
socket.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('message', function (data) {
        console.log(data);
    });

//断开连接callback
socket.on('disconnect', function () {
    console.log('Server has disconnected');
});
});

这是routes下的index.js

/*
* GET home page.
*/

exports.index = function (req, res) {

    res.render('index', { title: 'Express' });
};
6 回复

客户端js中

var socket = io.connect();
socket.on('news', function (data) {
  console.log(data);
  socket.emit('message', "hello ");
});

http://socket.io/#how-to-use

不是指客户端,是index.js文件,

现在socket都写在app.js里面,我想写在index.js文件里。

app.js

require(routes/index.js)(socket);

index.js

exports.index = function (socket) {

};
var express = require('express')
  , io = require('socket.io')
  , routes = require('./routes')
  , http = require('http')
  , user = require('./routes/user')
  , path = require('path')
  , partials = require('express-partials');
var app = express();


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(partials());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);
app.get('/users/:id?', user.list);

var server = http.createServer(app);

var socket = io.listen(server);

server.listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});


socket.on('connection', function (socket) {
    socket.emit('system', { msg: '欢迎来到聊天室!' });
    socket.on('message', function (data) {
        console.log(data);
    });

    //断开连接callback
    socket.on('disconnect', function () {
        console.log('Server has disconnected');
    });
});

require(routes/index.js)(socket);写哪里?

@charje 写在 var socket 后面

回到顶部