【问题标题】:Socket.io emit not working (by visiting URL)Socket.io 发出不工作(通过访问 URL)
【发布时间】:2019-09-28 16:05:18
【问题描述】:

我正在开发一个从外部硬件设备获取信号的应用。我通过将其重定向到我的应用程序中的某个 URL 来捕获此信号:'/impulse/:id'。

我能够捕捉到信号,但 app.get('/impulse/:id') 中的 emit 函数没有触发。控制台日志是...

如何使发射功能起作用?

下面是我的 server.js 脚本,我在其中捕获所有套接字信号并防止外部调用被重定向到索引页面。

...
const express = require('express');
const app = express();
const port = process.env.PORT || 8080; 
const socket = require('socket.io');

app.use(express.static(__dirname + '/public')); 
app.use('/api', appRoutes); 


mongoose.Promise = global.Promise;
mongoose.connect('mongodb://HERE IS MY DB INFO...', function(err) {
    if (err) {
        console.log('Not connected to the database: ' + err); // Log to console if unable to connect to database
    } else {
        console.log('Successfully connected to MongoDB'); // Log to console if able to connect to database
    }
});

var server = app.listen(port, function() {
    console.log('Running the server on port ' + port); // Listen on configured port
});

var io = socket(server);

io.on('connection', function(socket){

    socket.on('join', function(data){
        var gameroom = data.gameid;   
        console.log("joined: " + gameroom)     
        socket.join(gameroom);
    })

   //FUNCTION I WANT TO TRIGGER
    socket.on('impulse', function(data){
        console.log('IMPULSE')
        io.emit('impulseReceived', {

        })
    })

})

//PLACE WHERE I EMIT
app.get('/impulse/:id', function(req, res){
    console.log('Impulse Received')
    var time = req.query.TIME;
    var gameroom = req.params.id; 

    io.on('connect', function (socket) {
       socket.emit('impulse', {
       })
    })

    res.json({ success: true, message: 'received the time!'})
})

app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});

【问题讨论】:

  • 你弄明白了吗? @RutgerBms

标签: node.js angularjs express websocket socket.io


【解决方案1】:

全部替换

io.on('connect', function (socket) {
    socket.emit('impulse', {
    })
}

有了这个

io.emit('impulse', {})

【讨论】:

  • 感谢您的帮助。但是,我像你说的那样更改了代码(请参阅我的更改的主线程代码部分),但它仍然没有发送。我得到的唯一控制台输出是:“收到脉冲”。应该看到'IMPULSE'....
猜你喜欢
  • 2017-05-11
  • 2017-09-10
  • 1970-01-01
  • 2014-01-19
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 1970-01-01
相关资源
最近更新 更多