这是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 ");
});
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);写哪里?