在http get请求上发出socket.io消息(在Express.js中)

时间:2015-08-19 17:40:32

标签: node.js socket.io

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

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','来自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>

1 个答案:

答案 0 :(得分:-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.');
});