使用带有express 4和jade模板的socket.io

时间:2015-08-10 19:13:01

标签: node.js express socket.io pug

我试图将socket.io用于快递,但我无法使其正常工作

这是我的档案:

袋鼠:/app.js

var express = require('express');
var session = require('express-session');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//Routes files
var maketurn = require('./routes/maketurn');

var app = express();
var io = require('socket.io').listen(app.listen(3000));

// view engine setupe
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use('/maketurn', maketurn);
module.exports = app;

这是我的控制器(路由器)

袋鼠:/routes/maketurn.js

var express = require('express');
var router = express.Router();
var socketio = require('socket.io');

var app = express();
var server = app.listen(8088, function () {
    console.log("Express server listening on port and socket " + 3000);
});

var io = socketio.listen(server);

router
    .get('/', function (req, res) {
        io.on('connection', function (socket) {
            console.log('conectado el pendejo');
            socket.emit('news', {hello: 'world'});
            socket.on('my other event', function (data) {
            });
        });
        res.render('turns/maketurn', {title: 'Make Turn'});
    })

module.exports = router;

这是我的模板(客户端):

root:views/turns/maketurn.jade

extends ../layouts/turns

block content

    script.
        var socket = io.connect('httt://localhost:8088/maketurn');

        socket.on('news', function (data) {
            console.log(data);
            socket.emit('my other event', {my: 'data'});
        });
        socket.on('connection', function (data) {
            console.log(data);
            socket.emit('my other event', {my: 'data'});
        });

    .container
        form(method='post' action='#' role='form' id='turn')
            .wsn-form-control
                label Nombre y apellido
                input(name='name' type='text' id='name')

1 个答案:

答案 0 :(得分:0)

您必须将套接字事件处理程序移到路由器之外,请查看我几个小时前写给同一问题的用户的答案:

Socket.io node.js, how to log connection times avoid or account for page refresh/multiple sockets?

来自Socket.io网站的例子显示了同样的事情:

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

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});