【问题标题】:Emit socket.io message on http get request (in Express.js)在 http get 请求上发出 socket.io 消息(在 Express.js 中)
【发布时间】:2015-08-20 02:56:15
【问题描述】:

在我的 socket.io / express 应用程序中,我希望能够向 localhost:3000/send 发出 GET 请求,并向所有打开的连接发出消息,但是,此代码似乎不起作用:

var LISTENING_PORT = 1234;

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

//Example users
app.get('/messages', function(req, res){
  res.sendFile(__dirname + '/messages.html');
});

//Basket Reservation Namespace
var basket_reservation = io
  .on('connection', function(socket){
    socket.on('message', function(message){
      console.log('Received connection from user: ' + message);
      socket.emit('message', 'Connection started.');
    });

    app.get('/send', function(req, res){
      console.log('sending message to all');
      socket.emit('message', 'Message from GET /send');
      res.send('Message sent.');
    });
  });

http.listen(LISTENING_PORT, function(){
  console.log('listening on *:' + LISTENING_PORT);
});

具体是 socket.emit('message', 'Message from GET /send');不起作用。它上面和下面的行都会被调用。

这里是客户端:

<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript">
  var socket = io('http://localhost:1234/');
  socket.emit('message', 'hello');
  socket.on('message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
</script>

<h1>User #1</h1>


<ul id="messages"></ul>

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    我认为您的代码无法响应 /send 路由,因为您在 io.on('connection') 上异步声明它。

    我建议在 io.on('connection') 之外声明这个 - 我还没有运行我的代码 - 所以不确定它是否会运行:

    //Basket Reservation Namespace
    var basket_reservation = io
      .on('connection', function(socket){
        socket.on('message', function(message){
        console.log('Received connection from user: ' + message);
        socket.emit('message', 'Connection started.');
    });
    
    // Helper to send message (it uses closure to keep a reference to the io connetion - which is stored in basket_reservation in your code)
    var sendMessage = function (msg) {
      if (basket_reservation && basket_reservation.connected) {
        console.log('sending message to all');
        basket_reservation.emit('message', 'Message from GET /send');
      }
    };
    
    // Broadcast message
    app.get('/send', function(req, res){
      sendMessage(req.body.data);
      res.send('Message sent.');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 2012-06-28
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多