socket在http PUT上发出一个事件

时间:2016-10-07 09:15:45

标签: express socket.io

我正在使用expressjsnedbsocket.io。各种(非浏览器)客户端能够成功地PUT新值进入数据库。当发生这种情况时,我希望向连接到服务器的所有浏览器发出一条消息。我有以下代码,目前没有将消息发送回浏览器。

// on the server
//***************************************************************

// reachable to the world at http://server/foo
// clients can PUT data into the db
app.put('/foo', jsonParser, function(req, res, next) {
    if (!req.body) return res.sendStatus(400);

    db.insert(req.body, function (err, newDoc) {
        io.sockets.emit('PUT a new value', { added: newDoc._id });
        res.send('Success! Find it again with id: ' + newDoc._id);
    });
});

// reachable to the world at http://server/
// browser shows a dashboard of events
app.get('/', function(req, res, next) {
    // code to serve the dashboard here
});

io.sockets.on('connection', function (socket) {
    socket.on('foo', function (data) {
        io.sockets.emit('PUT a new value', data);
    })
});


// in the browser
//***************************************************************

var socket = io.connect('/');
socket.on('PUT a new value', function (data) {
    console.log(data);
});

数据从不同的非浏览器客户端成功插入数据库,但连接的浏览器没有收到更新。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我找到了一个我根本不喜欢的解决方案,但它有效。我们可以在中间件中将io对象添加到reqres,如下所示:

app.use(function (req, res, next) {
  req.io = io;
  next();
});

app.use('/', routes)之前,然后在我们的路由器模块中,我们" import" io对象:

    app.put('/foo', jsonParser, function(req, res, next) {
      if (!req.body) return res.sendStatus(400);

      db.insert(req.body, function (err, newDoc) {
        var io = req.io;   // HERE !!!
        io.sockets.emit('PUT a new value', { added: newDoc._id });
        res.send('Success! Find it again with id: ' + newDoc._id);
      });
    });

我知道,我知道......让我们找到别的东西: - )

答案 1 :(得分:0)

我有express generator生成的以下应用结构。我使用$ DEBUG=foo:* npm start

启动应用
.
|____app.js
|____bin
| |____www
|____data
|____LICENSE
|____node_modules
|____package.json
|____public
| |____stylesheets
| |____javascripts
| |____images
|____README.md
|____routes
| |____index.js
| |____readings.js
| |____sensors.js
| |____users.js
|____views
| |____error.hjs
| |____index.hjs

在app.js

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

// notice the `(io)` for the routes that need to be socket-aware
var routes = require('./routes/index');
var users = require('./routes/users');
var sensors = require('./routes/sensors');
var readings = require('./routes/readings')(io);

…

// start listening with socket.io
app.io.on('connection', function(socket){  
    console.log('a user connected');
});

module.exports = app;

然后在./routes/readings.js

var express = require('express');
var app = express();
var router = express.Router();

module.exports = function(io) {
    router.put('/', jsonParser, function(req, res, next) {
        if (!req.body) return res.sendStatus(400);

        db.insert(req.body, function (err, newDoc) {
            io.emit("reading", {id: newDoc._id});
            res.send('Success PUTting data! id: ' + newDoc._id);
        });
    });

    return router;
}

最后,在客户端的index.hjs模板中

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();
    socket.on('reading', function (data) {
        console.log(data);
    });
</script>

以上作品。当数据通过http PUT插入数据库时​​(请参阅readings.js),io.emit('reading', data)会发出一个事件,浏览器会收到该事件并在控制台中显示socket.on('reading', function (data) { … });